var metricsProcessing = false;
var pause;
var lastSeenPos = 0;
var threadId = '';
var streamId = '';
var streamEntryEachPage = 50;
var messageEntries = [];
var curRequest, curRequests = [];
var page = 1;
var retweetObj;
var currentFolderId = 0;
var advancedQuery = false;
var streamQuery = '';
var interval, myTrigger1, myTrigger2;
var lpercentM = 0, lpercentV = 0;
var objc;
var addStream = '<div class="mozaic-widget widget-new_stream" data-widget="new_stream" data-params="{&quot;title&quot;:&quot;Add a New Stream&quot;,&quot;channels&quot;:{&quot;/streams&quot;:&quot;/streams-2&quot;,&quot;/folders&quot;:&quot;/folders-1&quot;,&quot;/social_profiles&quot;:&quot;/social_profiles-5&quot;}}" data-guid="widget-637" data-initialized="true"><div><p>A stream is a realtime collection of mentions from 25+ social platforms. When creating streams, consider adding streams for your brand, products, competitors, market terms and campaigns.</p><button class="btn back-button" data-context="samsung" value=""><div class="tooltip fade top in"><div class="tooltip-arrow"></div><div class="tooltip-inner"><p>Use this stream type when building search expressions related to your Company. Track brands, products, key people, marketing campaigns, etc.</p><p class="tooltip-signals-info"><i class="icon-signals"></i>WILL COLLECT SIGNALS</p></div></div><i class="icon-folder-company-large"></i><span>Samsung</span></button><button class="btn back-button" data-context="unilever"><div class="tooltip fade top in"><div class="tooltip-arrow"></div><div class="tooltip-inner"><p>Use this stream type to stay on top of your competition! Track competitor\'s brands, products, key people, marketing campaigns, etc.</p><p class="tooltip-signals-info"><i class="icon-signals"></i>WILL COLLECT SIGNALS</p></div></div><i class="icon-folder-competitor-large"></i><span>Unilever</span></button><button class="btn back-button" data-context="coca-cola"><div class="tooltip fade top in"><div class="tooltip-arrow"></div><div class="tooltip-inner"><p>Use this stream type to track your industry. Pick specific search expressions and keywords that relate to your market in order to turn up insights on industry trends and opportunities to join the conversation.</p><p class="tooltip-signals-info"><i class="icon-signals"></i>WILL COLLECT SIGNALS</p></div></div><i class="icon-folder-market_term-large"></i><span>Coca-Cola</span></button></div></div>';
//var addStream = '<div class="mozaic-widget widget-new_stream" data-widget="new_stream" data-params="{&quot;title&quot;:&quot;Add a New Stream&quot;,&quot;channels&quot;:{&quot;/streams&quot;:&quot;/streams-2&quot;,&quot;/folders&quot;:&quot;/folders-1&quot;,&quot;/social_profiles&quot;:&quot;/social_profiles-5&quot;}}" data-guid="widget-637" data-initialized="true"><div><p>A stream is a realtime collection of mentions from 25+ social platforms. When creating streams, consider adding streams for your brand, products, competitors, market terms and campaigns.</p><button class="btn back-button" data-context="company" value=""><div class="tooltip fade top in"><div class="tooltip-arrow"></div><div class="tooltip-inner"><p>Use this stream type when building search expressions related to your Company. Track brands, products, key people, marketing campaigns, etc.</p><p class="tooltip-signals-info"><i class="icon-signals"></i>WILL COLLECT SIGNALS</p></div></div><i class="icon-folder-company-large"></i><span>Company/Product</span></button><button class="btn back-button" data-context="competitors"><div class="tooltip fade top in"><div class="tooltip-arrow"></div><div class="tooltip-inner"><p>Use this stream type to stay on top of your competition! Track competitor\'s brands, products, key people, marketing campaigns, etc.</p><p class="tooltip-signals-info"><i class="icon-signals"></i>WILL COLLECT SIGNALS</p></div></div><i class="icon-folder-competitor-large"></i><span>Competitor</span></button><button class="btn back-button" data-context="market_terms"><div class="tooltip fade top in"><div class="tooltip-arrow"></div><div class="tooltip-inner"><p>Use this stream type to track your industry. Pick specific search expressions and keywords that relate to your market in order to turn up insights on industry trends and opportunities to join the conversation.</p><p class="tooltip-signals-info"><i class="icon-signals"></i>WILL COLLECT SIGNALS</p></div></div><i class="icon-folder-market_term-large"></i><span>Market Term</span></button><button class="btn back-button" data-context="keyword_search"><div class="tooltip fade top in"><div class="tooltip-arrow"></div><div class="tooltip-inner"><p>Use this stream type for streams you don�t want to look regularly or for streams that does not fit into one of the other categories</p><p class="tooltip-signals-info"><i class="icon-forbidden"></i>WILL NOT COLLECT SIGNALS</p></div></div><i class="icon-add-search-stream icon-folder-keyword_search-large"></i><span>Keyword Search</span></button></div></div>';
var addS = '<p class="mt-25">In addition to the keyword search based streams above, you can connect social account streams below.</p><button class="btn back-button" data-context="social_accounts" data-platform="twitter"><div class="tooltip fade top in"><div class="tooltip-arrow"></div><div class="tooltip-inner"><p class="tooltip-signals-info"><i class="icon-forbidden"></i>WILL NOT COLLECT SIGNALS</p></div></div><i class="icon-add-twitter-stream"></i><span>Twitter Account</span></button><button class="btn back-button" data-context="social_accounts" data-platform="facebook"><div class="tooltip fade top in"><div class="tooltip-arrow"></div><div class="tooltip-inner"><p class="tooltip-signals-info"><i class="icon-forbidden"></i>WILL NOT COLLECT SIGNALS</p></div></div><i class="icon-add-facebook-stream"></i><span>Facebook Page</span></button><button class="btn back-button" data-context="social_accounts" data-platform="linkedin"><div class="tooltip fade top in"><div class="tooltip-arrow"></div><div class="tooltip-inner"><p class="tooltip-signals-info"><i class="icon-forbidden"></i>WILL NOT COLLECT SIGNALS</p></div></div><i class="icon-add-linkedin-stream"></i><span>LinkedIn Group</span></button><button class="btn back-button" data-context="social_accounts" data-platform="googleplus"><div class="tooltip fade top in"><div class="tooltip-arrow"></div><div class="tooltip-inner"><p class="tooltip-signals-info"><i class="icon-forbidden"></i>WILL NOT COLLECT SIGNALS</p></div></div><i class="icon-add-googleplus-stream"></i><span>Google+ Page</span></button>';
var replyBox = '<div class="mozaic-widget widget-reply_form" data-widget="reply_form"><p class="mention-text original-mention"></p><p class="errors"></p><div class="form"><form class="bbf-form"><fieldset><legend></legend><div><div><label for="c2844_message" class="label-form">Message</label><div><textarea id="c2844_message" name="message" type="text" style="width: 330px"></textarea></div><div class="help-block">Type the message you want to post</div></div></div></fieldset></form></div><input type="submit" class="btn btn-red commit" value="Reply"></div>';
var completeBox = '<div class="mozaic-widget widget-complete_form"><p class="mention-text original-mention"></p><p class="errors"></p><div class="form"><form class="bbf-form"><fieldset><legend></legend><div><div><label for="c2844_action" class="label-form">Action</label><div><textarea id="c2844_action" name="message" type="text" style="width: 330px"></textarea></div><div class="help-block">Enter the solution of the task</div></div></div></fieldset></form></div><input type="submit" class="btn btn-red commit" value="Save"></div>';
var addTagGroup = '<div class="mozaic-widget widget-addgroup_form" data-widget="addgroup_form"  ><p class="mention-text original-mention"></p><p class="errors"></p><div class="form"><form class="bbf-form"><fieldset><legend></legend><div><div><label for="inviteEmail" class="label-form">Name<span style="color: red">*</span></label><div><input type="text" class="required" id="tagGroupName" name="name" style="width: 330px" /></div><div class="help-block">Name your tag group</div></div></div></fieldset></form></div><div class="submit-form" style="position: relative;"><input type="submit" class="btn btn-red commit" value="Save"></div></div>';
var addTag = '<div class="mozaic-widget widget-addtag_form"><p class="errors"></p><div class="form"><form class="bbf-form"><fieldset><legend></legend><div><div><label for="name" class="label-form">Tag Name<span style="color: red">*</span></label><div><input type="text" class="required" id="ftagName" name="name" style="width: 330px" /></div><div class="help-block">Enter tag name</div></div><div><label for="inviteEmail" class="label-form">Keywords<span style="color: red"></span></label><div><div class="suggest-input"><div class="data-presenting"><span><input type="text" id="ftagKeywords" name="keyword" style="width: 330px" /></span></div></div></div><div class="help-block">Enter keywords, separate with comma \',\'</div></div><div style="display: none;"><label for="moveTo" class="label-form">Group</label><div><select id="moveTo" style="width: 330px"></select></div><div class="help-block">Select a group to move to</div></div></div></fieldset></form></div><div class="submit-form" style="position: relative;"><input type="submit" class="btn btn-red commit" value="Save"></div></div>';
var sendEmailBox, sendSMSBox;
var sendInvitationBox;
var curSendButton;
var replyPostID, replyMessage;
var completeTaskId;
var postStatus, addTask, addStreamBC, addStreamS1, addStreamS2, addStreamS3, shareMessage, shareViaEmail, currentPost;
var messageType, messageLink, messageContent;
var addStreamPostData = new Array();
var streamType;
var query = new Array();
var filterSource = new Array();
var viewport = "";
var mainView = "";
var dateFrom;
var dateTo;
var messageId;
var streamId;
var sstreamId;
var folderId = '';
var streamName = '';
var addTaskMessageId;
var addTaskStreamId;
var thisUl;
var firstload = true;
var needToNavigate = true;
var stream = new Array();
var shareMessageId = '';
var shareStreamId = '';
var metricsLoadCompleted = false;
var documentReady = true;
var dataMail = '';
var replyMail = '';
var groups, tags;
var globalFilter;
var finishLoading = false;
var colLabelFormat = '', colTrendLabelFormat = '';
$(document).ready(function() {
    if (firstload) {
        params = window.location.href.split("#");
        if (params.length > 1)
            navigateURL(params[1]);
        else
            hideloading();
        firstload = false;
    }
});
window.onerror = function(e) {

}

$.post("/ajax/postStatus", function(data) {
    postStatus = data;
});
$.post("/ajax/addTask", function(data) {
    addTask = data;
});
$.post("/ajax/shareMessage", function(data) {
    shareMessage = data;
});
$.post("/ajax/shareViaEmail", function(data) {
    shareViaEmail = data;
});
$.post("/ajax/addStreamBC", function(data) {
    addStreamBC = data;
});
$.post("/ajax/addStreamS1", function(data) {
    addStreamS1 = data;
});
$.post("/ajax/addStreamS2", function(data) {
    addStreamS2 = data;
});
$.post("/ajax/addStreamS3", function(data) {
    addStreamS3 = data;
});
$.post("/ajax/sendEmailBox", function(data) {
    sendEmailBox = data;
});
$.post("/ajax/sendSMSBox", function(data) {
    sendSMSBox = data;
});
$.post("/ajax/inviteFriendBox", function(data) {
    sendInvitationBox = data;
})

$(document).on('click', '.delete-task', function(e) {

});

$(document).on('click', '.btn-red.commit', function(e) {
    $('.bbf-form').submit();
});
$(document).on('click', '.btn-group', function(e) {
    $('.btn-group.open').removeClass('open');
    $(this).addClass('open');
});
$(document).on('mouseleave', '.mention-container', function(e) {
    $(".mention-container .btn-group").removeClass('open');
});
$('#modal').css('display', 'block');
$(document).on('click', '.post-button', function(e) {
    if ($('.modal-body').html() !== postStatus) {
        $('.modal-title').html("Post");
        $('.modal-body').html(postStatus);
    }
    $('.modal-dialog').addClass("social_post_form_wrapper");
    $('.modal-backdrop').css('z-index', '9999');
    $('#modal').css('z-index', '10000');
    $('.modal-backdrop').css('display', 'block');
    $('.modal-backdrop').addClass('in');
    $('#modal').addClass("in");
});
$(document).on('click', '.add-stream', function(e) {
    streamSources = new Array();
    streamQuery = '';
    if ($('.modal-body').html() !== addStream) {
        $('.modal-title').html("Add a New Stream");
        $('.modal-body').html(addStream);
    }
    $('.modal-backdrop').css('display', 'block');
    $('.modal-backdrop').addClass('in');
    $('.modal-backdrop').css('z-index', '9999');
    $('#modal').css('z-index', '10000');
    $('#modal').addClass("in");
    if ($('.modal-body').html() !== addStreamS1) {
        $('.modal-title').html("Add A New Stream");
        $('.modal-body').html(addStreamBC + addStreamS1);
    }
    $('.modal-backdrop').css('display', 'block');
    $('.modal-backdrop').addClass('in');
    $('.modal-backdrop').css('z-index', '9999');
    $('#modal').css('z-index', '10000');
    $('#modal').addClass("in");
    $('.modal-body').html(addStreamBC + addStreamS1);
    folderId = '';
    streamId = '';
    streamName = '';
    needToNavigate = true;
    $('.modal-body .btn-red.commit').click(function(e) {
        if ($('.advanced-query a').html() == 'Advanced query') {
            query = new Array();
            query['all'] = $('#c1195_all').val();
            query['any'] = $('#c1195_any').val();
            query['none'] = $('#c1195_none').val();
            advancedQuery = false;
        }
        else {
            streamQuery = query = $('#c1195_query').val();
            advancedQuery = true;
        }
        loadStream(2);
    });
});
$(document).on('click', '.add-task', function(e) {
    if ($('.modal-body').html() !== addTask) {
        $('.modal-title').html("Add a Task");
        $('.modal-body').html(addTask);
        addTaskMessageId = $(this).attr('messageid');
        addTaskStreamId = $(this).attr('streamid');
    }

    currentPost = $(this).parents('.mention-right-container').find('.mention-text')[0].innerText;
    currentPost = currentPost.replace('Read maore', '');
    curLink = $(this).parents('.mention-right-container').find('a:first').attr('href');
    $('.modal-backdrop').css('display', 'block');
    $('#modal').css('width', '380px');
    $('#modal').css('margin-left', '-190px');
    $('.modal-backdrop').addClass('in');
    $('.modal-backdrop').css('z-index', '9999');
    $('#modal').css('z-index', '10000');
    $('#modal').addClass("in");
});
$(document).on('click', '.icon-close-modal', function(e) {
    var datadismiss = $(this).attr('data-dismiss');
    $('#' + datadismiss).removeClass('in');
    startInterval(1);
});
function startInterval(i) {
    if (i === 1)
        interval = setInterval("interval1()", 200);
    if (i === 2)
        interval = setInterval("interval2()", 200);
}

function interval1() {
    $('.modal-backdrop').removeClass('in');
    clearInterval(interval);
    startInterval(2);
}

function interval2() {
    $('.modal-backdrop').css('z-index', '0');
    $('#modal').css('z-index', '-10000');
    $('#modal').css('width', '');
    $('#modal').css('margin-left', '');
    $('.modal-backdrop').css('display', 'none');
    $('.modal-dialog').removeClass('social_post_form_wrapper');
    //    $('#modal').css('display', '');
    clearInterval(interval);
}

$(document).on('mouseleave', '.dropdown-menu', function(e) {
    $(this).parent('.btn-group').removeClass('open');
});
function loadStream(step) {
    switch (step) {
        case 1:
            streamId = '';
            folderId = 1;
            streamName = '';
            $('li#step-0').attr('class', 'enabled active');
            $('.modal-body .btn').click(function(e) {
                var type = $(this).attr('data-context');
                streamType = type;
                $('.modal-body').html(addStreamBC + addStreamS1);
                $('.modal-title').html('Add a new <i class="icon-folder-title icon-folder-' +
                        type + '"></i><b>' + capitaliseFirstLetter(type) + '</b> Stream');
                $('.modal-body .btn-red.commit').click(function(e) {
                    if ($('.advanced-query a').html() == 'Advanced query') {
                        query = new Array();
                        query['all'] = $('#c1195_all').val();
                        query['any'] = $('#c1195_any').val();
                        query['none'] = $('#c1195_none').val();
                        advancedQuery = false;
                    }
                    else {
                        query = $('#c1195_query').val();
                        advancedQuery = true;
                    }
                    loadStream(2);
                });
            });
            break;
        case 2:
            $('li#step-0').attr('class', 'enabled selected');
            $('li#step-0').click(function(e) {
                $('.wizard-content').html(addStreamS1);
            });
            $('li#step-1').attr('class', 'enabled active');
            $('.wizard-content').html(addStreamS2);
            if (streamSources.length > 0) {
                $('.additional-sources-container .blank-state').css('display', 'none');
                for (i = 0; i < streamSources.length; i++) {
                    $('.additional-sources-container ul.items').append(
                            "<li>\
                            <strong>" + streamSources[i] + "</strong><a class=\"removeSource\">remove</a>\
                            <br><a href=" + streamSources[i] + ">" + streamSources[i] + "</a>\
                        </li>"
                            );
                }
            }
            $('.modal-body .btn-red.commit').click(function(e) {
                filterSource["language"] = $('#c2108_default_language').val();
                filterSource["location"] = $('#c2108_default_location').val();
                filterSource["generator"] = $('#c2108_default_generator').val();
                loadStream(3);
            });
            break;
        case 3:
            $('li#step-0').attr('class', 'enabled selected');
            $('li#step-0').click(function(e) {
                $('.wizard-content').html(addStreamS1);
            });
            $('li#step-1').attr('class', 'enabled selected');
            $('li#step-1').click(function(e) {
                $('.wizard-content').html(addStreamS2);
            });
            $('li#step-2').attr('class', 'enabled active');
            $('.wizard-content').html(addStreamS3);
            $('#c2148_name').val(streamName);
            if (folderId != '')
                $('#c2148_folder_id').val(folderId);
            else
                $('#c2148_folder_id').val(1);
            $('.modal-body .btn-red.commit').click(function(e) {
                addStreamPostData["streamType"] = streamType;
                addStreamPostData["query"] = query;
                addStreamPostData["filterSource"] = filterSource;
                addStreamPostData["streamName"] = $('#c2148_name').val();
                addStreamPostData["folderId"] = $('#c2148_folder_id').val();
                loadStream(4);
                return;
            });
            break;
        case 4:
            streamData = addStreamPostData;
            userId = currentUserId;
            addStreamPostData["userId"] = userId;
            name = addStreamPostData["streamName"];
            type = 1;
            streamQuery = '';
            if (advancedQuery)
                streamQuery = '\t' + addStreamPostData["query"];
            else
                streamQuery = addStreamPostData["query"];
            language = 2;
            if (query['all'] != undefined) {
                streamQuery = createQuery(addStreamPostData["query"]);
            }
            streamLocation = addStreamPostData["filterSource"]['location'];
            streamPlatform = addStreamPostData["filterSource"]['platform'];
            externalSources = streamSources.join(';');
            folderId = addStreamPostData["folderId"];
            url = "/m";
            var pl = new SOAPClientParameters();
            pl.add("typedata", "stream");
            pl.add('streamId', streamId);
            pl.add("userId", userId);
            pl.add("name", name);
            pl.add('type', type);
            pl.add('query', streamQuery);
            pl.add('language', language);
            pl.add('location', streamLocation);
            pl.add('platform', streamPlatform);
            pl.add('externalSources', externalSources);
            pl.add('folderId', folderId);
            SOAPClient.invoke(url, "saveStream", pl, true, addStreamCompleted);
            $('#modal').removeClass('in');
            startInterval(1);
            break;
    }
}

function addStreamCompleted(r) {
    $.post('folder', function(data) {
        $('.widget-directory_list').first().html(data);
        navigateFolder();
        var pl = new SOAPClientParameters();
        SOAPClient.invoke("m/", "getFolder", pl, true, getfolder_callback);
        if (needToNavigate)
            navigateURL('stream/' + Base64.encode(r.streamId));
        else {
            fldid = $('#folderlist .expanded-folder').parents('li').attr('data-id');
            var pl = new SOAPClientParameters();
            pl.add('folderid', fldid);
            SOAPClient.invoke("/m/", "listStream", pl, true, liststream_callback);
            needToNavigate = true;
        }
    });
}

function Stream(userId, name, type, query, language, location, platform, externalSources, folderId) {
    this.userId = userId;
    this.name = name;
    this.type = type;
    this.query = query;
    this.language = language;
    this.location = location;
    this.platform = platform;
    this.externalSources = externalSources;
    this.folderId = folderId;
}

function capitaliseFirstLetter(string)
{
    return string.charAt(0).toUpperCase() + string.slice(1);
}

function loadViewport(data) {
    if (data.indexOf('<a class="forgot-password-link"') != -1)
        window.location.reload(true);
    $('#action-menu-content').html(data);
    param = window.location.href.split('#')[1];
    params = param.split('/');
    streamId = params[1];
    if (params[0] === 'stream' || params[0] === 'metrics' || params[0] === 'alert' || params[0] === 'compare' || params[0] === 'sentiment' || params[0] === 'engagement') {
        var streamId = params[1];
        var filterdata = {};
        filterdata.dateFrom = $('#from').datepicker().val().replace(/\//g, '-');
        filterdata.dateTo = $('#to').datepicker().val().replace(/\//g, '-');
        var filter = JSON.stringify(filterdata);
        $.post('/ws/topsourcesdata/' + streamId + '/' + filter, function(data) {
            if (data === 'null')
                return;
            var sources = JSON.parse(data);
            $('ul.sources-list li:not(:first)').remove();
            for (i = 0; i < sources.length; i++) {
                $('ul.sources-list').append('<li style="line-height: 21px;" data-value="' + sources[i].source + '" title="' + sources[i].title + '" class="back-list-link">\
                                                    <a>\
                                                        <i class="icon-circle-list"></i>\
                                                        ' + sources[i].title + '\
                                                    </a>\
                                                </li>');
            }
        });
    }
    if (params[0].toLowerCase() == "stream")
        if ($('.toggle q').html() == 'ON')
            preview();
        else
            $('#action-menu-content').animate({'opacity': 1}, 100);
    if ($('.query-container').length > 0)
        if ($('.query-container').height() >= $('.query-container')[0].scrollHeight) {
            $('.query-container').css('height', 'auto');
            $('.three-dots').css('display', 'none');
        }
}

function loadMainView(data) {
    if (data.indexOf('<a class="forgot-password-link"') != -1)
        window.location.reload(true);
    param = window.location.href.split('#')[1];
    params = param.split('/');

    $('#controller-container').html(data.trim());



    if ($('ul.widget-signals').length > 0) {
        $($('ul.widget-signals')[0].childNodes[0]).remove();
    }
    if (params[0].toLowerCase() == "stream")
        if ($('.toggle q').html() == 'ON')
            preview();
    $('#controller-container').animate({'opacity': 1}, 500);
    $('.background-loading').animate({'opacity': 0}, 100);
    hideloading();
    if (params[0].toLowerCase() == "stream" || params[0].toLowerCase() == "metrics" || params[0].toLowerCase() == "sentiment") {
        applyFilter();
    }

    if ($('.mention-text:not(.url-parsed)').length > 0) {
        $('.mention-text:not(.url-parsed)').each(function() {
            $(this).html(parseURL($(this).html()));
            $(this).addClass("url-parsed");
            $(this).attr('text', $(this).html());
        });
    }
}

$('.top-nav-menu a').click(function(e) {
    param = String($(this).children("span").html()).toLowerCase();
    navigateURL(param);
});

function navigateURL(param) {
    advancedQuery = false;
    hidePreview();
    params = param.split('/');
    $('#analytics-link-widget li.active-section').removeClass('active-section');
    if (params[0].toLowerCase() == "stream")
        if ($('.toggle q').html() == 'OFF') {
            $('#action-menu-content').animate({'opacity': 0}, 100);
            if (!$(document.body).hasClass('preview'))
                $(document.body).removeClass('preview');
        }
        else {
            if (!$(document.body).hasClass('preview'))
                $(document.body).addClass('preview');
        }
    $('#controller-container').animate({'opacity': 0}, 100);
    $('.background-loading').animate({'opacity': 1}, 100);
    if (window.location.href.split('#')[1] != undefined)
        if (window.location.href.split('#')[1].toLowerCase() != param.toLowerCase())
            history.pushState({page: 1}, param, "#" + param);
    //window.location = "#" + param;

    var sstreamId = '';
    if (params[1] != undefined) {
        sstreamId = '/' + params[1];
        navigateFolder();
    }
    param = params[0];
    switch (params[0]) {
        case "alert":
            $(document.body).removeClass('preview');
            hidePreview();
            break;
        case "stream":
            if ($('#stage q').html() == "ON")
                if (!$(document.body).hasClass('preview'))
                    $(document.body).addClass('preview');
            break;
        case "activity":
            $(document.body).removeClass('preview');
            break;
        case "reports":
            $(document.body).removeClass('preview');
            break;
        case "metrics":
            hidePreview();
            $(document.body).removeClass('preview');
            break;
        case "settings":
            $(document.body).removeClass('preview');
            break;
        case "home":
            $(document.body).removeClass('preview');
            break;
        case "compare":
            $(document.body).removeClass('preview');
            $('#compare-link-widget').parent().addClass('active-section');
            break;
        case "engagement":
            $(document.body).removeClass('preview');
            $('#engagement-link-widget').parent().addClass('active-section');
            break;
        case "sentiment":
            $(document.body).removeClass('preview');
            break;
        default:
            $(document.body).removeClass('preview');
            break;
    }
    loadViewPort(param, sstreamId);
}

function navigateFolder() {
    param = window.location.href.split('#')[1];
    if (param.indexOf('/') != -1) {
        params = param.split('/');
        $('.keyword').each(function() {
            if ($(this).attr('data-id') == Base64.decode(params[1]))
                $(this).parents('.widget-folder_with_streams').children('a').addClass('expanded-folder');
        });
    }
}

window.onhashchange = function(data) {
    params = window.location.href.split("#");
    if (params.length > 0) {
        navigateURL(params[1]);
    }
}

var curCompleteButton;
$(document).on('click', 'button.mark-complete', function(e) {
    if ($(this).text() === " Mark Complete") {
        $('.modal-title').html("Complete task");
        $('.modal-body').html(completeBox);
        curTaskId = $(this).attr('taskid');

        $('.modal-backdrop').css('display', 'block');
        $('#modal').css('width', '380px');
        $('#modal').css('margin-left', '-190px');
        $('.modal-backdrop').addClass('in');
        $('.modal-backdrop').css('z-index', '9999');
        $('#modal').css('z-index', '10000');
        $('#modal').addClass("in");
        curCompleteButton = $(this);
    }
    else {
        var pl = new SOAPClientParameters();
        pl.add("id", $(this).attr('taskId'));
        SOAPClient.invoke("/m/", "undoComplete", pl, true, addCompleted);
        $(this).parents('.stream-task-container').removeClass("completed");
        $(this).html("<i class=\"icon-complete-task\"></i> Mark Complete");
        text = $(this).parents('.stream-task-container').find(".mention-text").attr('text');
        $(this).parents('.stream-task-container').find(".mention-text").text(text);
    }
});
$(document).on('click', 'button.delete-task', function(e) {
    var pl = new SOAPClientParameters();
    pl.add("id", $(this).attr('taskId'));
    SOAPClient.invoke("/m/", "deleteTask", pl, true, deleteCompleted);
    $(this).parents('li').remove();
});
$(document).on('submit', '.widget-task_form .bbf-form', function(e) {
    $(this).find('.commit').attr('disabled', 'disabled');
    $(this).find('.background-loading-small').removeClass('hide');
    //Add task
    var userId = currentUserId;
    var taskType = $(this)[0].category_id.value;
    var taskDescription = $(this)[0].description.value;
    var assignedTo = $(this)[0].assigned_to.value;
    var department = $(this)[0].department.value;
    var pl = new SOAPClientParameters();
    pl.add("userId", userId);
    pl.add("taskType", taskType);
    pl.add("taskDescription", taskDescription);
    pl.add("assignedTo", assignedTo);
    pl.add("messageId", addTaskMessageId);
    pl.add("streamId", addTaskStreamId);
    pl.add("post", '<a href="' + curLink + '" target="_blank">' + currentPost + '</a>');
    pl.add("department", department)
    SOAPClient.invoke("/m/", "addTask", pl, true, addCompleted);
    return false;
});

$(document).on('submit', '.widget-social_form .bbf-form', function(e) {
    $(this).find('.commit').attr('disabled', 'disabled');
    $(this).find('.background-loading-small').removeClass('hide');
    var pl = new SOAPClientParameters();
    messageContent = document.forms[0].description.value;
    switch (messageType) {
        case 'retweet':
            pl.add("messageId", shareMessageId);
            pl.add("streamId", shareStreamId);
            pl.add("message", messageContent);
            SOAPClient.invoke("/m/", "postTweet", pl, true, test_callback);
            break;
        case 'facebook':
            pl.add("messageId", shareMessageId);
            pl.add("streamId", shareStreamId);
            pl.add("message", messageContent);
            pl.add("link", messageLink);
            SOAPClient.invoke("/m/", "postFacebookStatus", pl, true, test_callback);
            break;
        case 'linkedin':
            pl.add("messageId", messageId);
            pl.add("streamId", streamId);
            pl.add("message", messageContent + '\n' + messageLink);
            SOAPClient.invoke("/m/", "postLinkedInStatus", pl, true, test_callback);
            break;
    }
    return false;
});

function addCompleted(r) {
    showMessage('Task assigned');
    var timeout = setTimeout(function() {
        $('#modal').removeClass('in');
        startInterval(1);
    }, 500);
}

function deleteCompleted(r) {

}

function clearFilter() {
    $('#from').datepicker('setDate', orgDateFrom);
    $('#to').datepicker('setDate', orgDateTo);
    $('#user-filter-widget a').first().attr('data-value', 0);
    $('#user-filter-widget a span').first().html('All Users');
    $('#language-filter-widget a').first().attr('data-value', globalLanguage);
    $('#platform-filter-widget a').first().attr('data-value', 0);
    $('#source-filter-widget a').first().attr('data-value', 0);
    $('#platform-filter-widget a span').first().html('All Platforms');
    $('#source-filter-widget a span').first().html('All Sources');
    $('#language-filter-widget li').each(function(d) {
        if ($(this).attr('data-value') == globalLanguage)
            $('#language-filter-widget a span').html(this.innerText);
    });
    $('#tag-filter-widget a').attr('data-value', '0');
    $('#tag-filter-widget a span').html('All Tags');
    $('#tag-filter-widget .selected').removeClass('selected');
    $('#source-filter-widget .selected').removeClass('selected');
    $('.radio-options-sentiment .selected').removeClass('selected');
    $('#user-filter-widget .selected').removeClass('selected');
    $('.filter-button.selected').removeClass('selected');
    var streamId = window.location.href.split('#')[1].split('/')[1];
    if (window.location.href.split('#')[1].split('/')[0].toUpperCase() === 'MONITORING') {
        streamId = 'monitoring';
    }
    setCookie('stream[' + streamId + '][datefrom]', $("#from").datepicker().val(), 1);
    setCookie('stream[' + streamId + '][dateto]', $("#to").datepicker().val(), 1);
    applyFilter();
}

function applyFilter(element) {

    noMoreMessage = false;
    pause = false;
    view = window.location.href.split('#')[1].split('/')[0];
    sstreamId = window.location.href.split('#')[1].split('/')[1];
    filter = "";
    var messageActionFilter = '';
    if ($('#mentions-link-widget ul.message-action-filter .active-section').length !== 0)
        messageActionFilter = '?filter=' + $('#mentions-link-widget ul.message-action-filter .active-section i').attr('class').split(' ')[0].split('icon-main-menu-')[1];
    if (element) {
        filter = element.parents('.opened').attr('id');
        element.parents('.opened').removeClass('opened');
        var dataToCompare = '0';
        if (element.parents('.filter-overlay').parent().attr('id') == 'language-filter-widget')
            dataToCompare = globalLanguage;
        if (element.attr('data-value') !== dataToCompare) {
            if (!element.parents('.filter-overlay').prev().hasClass('selected'))
                element.parents('.filter-overlay').prev().addClass('selected');
        }
        else
            element.parents('.filter-overlay').prev().removeClass('selected');
    }
    if (view.toUpperCase() === "MONITORING") {
        sstreamId = 'monitoring';
    }
    var dFromCookie = getCookie('stream[' + sstreamId + '][datefrom]');
    var dToCookie = getCookie('stream[' + sstreamId + '][dateto]');
    if (dFromCookie !== undefined && dFromCookie !== '')
        $('#from').datepicker('setDate', dFromCookie);
    if (dToCookie !== undefined && dToCookie !== '')
        $('#to').datepicker('setDate', dToCookie);

    dateFrom = $('#from').datepicker().val().replace(/\//g, '-');
    dateTo = $('#to').datepicker().val().replace(/\//g, '-');

    dateFText = $.datepicker.parseDate('dd-mm-yy', dateFrom).toString().substring(4, 10);
    dateTText = $.datepicker.parseDate('dd-mm-yy', dateTo).toString().substring(4, 10);
    $('#selected_date').text(dateFText + ' - ' + dateTText);

    var filterdata = {};
    filterdata.dateFrom = $('#from').datepicker().val().replace(/\//g, '-');
    filterdata.dateTo = $('#to').datepicker().val().replace(/\//g, '-');
    var filter = JSON.stringify(filterdata);
    $.post('/ws/topsourcesdata/' + sstreamId + '/' + filter, function(data) {
        if (data === 'null')
            return;
        var sources = JSON.parse(data);
        $('ul.sources-list li:not(:first)').remove();
        for (i = 0; i < sources.length; i++) {
            $('ul.sources-list').append('<li style="line-height: 21px;" data-value="' + sources[i].source + '" title="' + sources[i].title + '" class="back-list-link">\
                                                    <a>\
                                                        <i class="icon-circle-list"></i>\
                                                        ' + sources[i].title + '\
                                                    </a>\
                                                </li>');
        }
    });
    if (dFromCookie !== undefined && dToCookie !== undefined && (dFromCookie !== orgDateFrom || dToCookie !== orgDateTo)) {
        $('#date-filter-widget>div').addClass('selected');
    }
    else
        $('#date-filter-widget>div').removeClass('selected');

    sentiment = $('#sentiment-filter-widget a.selected').attr('data-value');
    if ($('#sentiment-filter-widget a.selected').length == 0)
        sentiment = 0;
    language = $('#language-filter-widget').find('a').attr('data-value');
    type = $('#platform-filter-widget').find('a').attr('data-value');
    tag = $('#tag-filter-widget').find('a').attr('data-value');
    source = $('#source-filter-widget').find('a').attr('data-value');
    userId = $('#user-filter-widget').find('a').attr('data-value');
    //thismonth = $('#thismonth-filter-widget a.selected').attr('data-value');
    var userDefault = true;
    if ($('#user-filter-widget a').first().attr('data-value') !== undefined)
        if ($('#user-filter-widget a').first().attr('data-value') != 0)
            userDefault = false;
    if (view.toUpperCase() !== "MONITORING") {
        if (typeof orgDateFrom != 'undefined' && typeof orgDateTo != 'undefined') {
            if (dateFrom == orgDateFrom && dateTo == orgDateTo &&
                    ($('#language-filter-widget a').first().attr('data-value') == globalLanguage) &&
                    ($('#tag-filter-widget a').first().attr('data-value') == 0) && $('#sentiment-filter-widget a.selected').length == 0 && $('#platform-filter-widget a').first().attr('data-value') == 0 &&
                    ($('#source-filter-widget a').first().attr('data-value') == 0) && userDefault) {
                $('.widget-search_filter_list .selected').removeClass('selected');
                $('.clear-filters').css('display', 'none');
            }
            else
                $('.clear-filters').css('display', 'block');
        }
    }
    else {
        if (typeof orgDateFrom != 'undefined' && typeof orgDateTo != 'undefined') {
            if (dateFrom == orgDateFrom && dateTo == orgDateTo &&
                    ($('#user-filter-widget a').first().attr('data-value') == 0)) {
                $('.clear-filters').css('display', 'none');
            }
            else
                $('.clear-filters').css('display', 'block');
        }
    }
    $('#selected_date').attr('dateFrom', dateFrom);
    $('#selected_date').attr('dateTo', dateTo);
    switch (view) {
        case "stream":
            page = 1;
            $('.list-viewport').animate({'opacity': 0}, 100);
            $('.background-loading').animate({'opacity': 1}, 100);
            if (curRequest !== undefined)
                curRequest.abort();
            pause = true;
            lastSeenPos = 0;
            pause = true;
            if (curRequest !== undefined)
                curRequest.abort();
            $('.loading').height(30);
            $('.list-viewport ul.widget-signals').html('');
            curRequest = loadpStream(sstreamId, dateFrom, dateTo, 0, streamEntryEachPage, language, tag, sentiment, '', type, source, function(text) {
                if ($('.background-loading').css('opacity') == 1) {
                    $('.background-loading').animate({'opacity': 0}, 100);
                    $('.list-viewport').animate({'opacity': 1}, 500);
                }
                var splitText = ' |||||| ';
                var newPos = text.indexOf(splitText, lastSeenPos + 1);
                while (newPos !== -1) {
                    var element = '';
                    if (lastSeenPos > 0)
                        element = text.substring(lastSeenPos + splitText.length, newPos);
                    else
                        element = text.substring(lastSeenPos, newPos);
                    $('.list-viewport ul.widget-signals').append(element.replace(/\|\|\|\|\|\|/g, ''));
                    $('.mention-text:not(.url-parsed), .main-reply-content:not(.url-parsed)').each(function() {
                        $(this).html(parseURL($(this).html()));
                        $(this).addClass("url-parsed");
                        $(this).attr('text', $(this).html());
                    });
                    lastSeenPos = newPos;
                    newPos = text.indexOf(' |||||| ', lastSeenPos + 1);
                }
            }, function(data) {
                $('.loading').height(0);
                if (window.location.href.split('#')[1].split('/')[0] !== 'stream')
                    return;
                if ($('.list-viewport ul.widget-signals').length === 0)
                    $('.list-viewport').html('<ul class="mozaic-widget list mozaic-initialized widget-signals"></ul><div class="loading" style="width: 1026px; height: 0;"><div class="loading-percent" style="width: 0%;"></div><h3>Loading...</h3></div><style>.loading-percent {width: 0%;background-color: #008000;height: 2px;-webkit-transition: all 0.3s ease-in-out;}.loading {text-align: center;position: fixed;bottom: 0px;z-index: 20000;width: 100%;height: 0%;-webkit-transition: all 0.1s ease-in-out;-moz-transition: all 0.1s ease-in-out;-o-transition: all 0.1s ease-in-out;transition: all 0.1s ease-in-out;}</style>');
                if (data.trim() === 'Your query has no result! Try again!' || data.trim() === '') {
                    noMoreMessage = true;
                    $('.list-viewport').css('overflow-y', 'hidden');
                    var ul = $('.list-viewport ul.widget-signals');
                    ul.html('<div class="no-result" style="width: 300px;font-size: 13pt;text-align: center;padding: 30px 10px;vertical-align: middle;margin: 150px auto;background: #FFF;border: 1px solid #BBB;border-radius: 2px;box-shadow: 1px 1px 1px #BBB;"><h1 style="line-height: 70pt; font-size: 49pt;-webkit-transform: rotate(90deg);-moz-transform: rotate(90deg);-o-transform: rotate(90deg);transform: rotate(90deg);">:-(</h1><h3>Sorry!</h3>There\'s no data yet.<br>Please check back later...</div>');
                    $('.background-loading').animate({'opacity': 0}, 100);
                    $('.list-viewport').animate({'opacity': 1}, 500);
                    return;
                }
                pause = false;
                noMoreMessage = false;
                $('.list-viewport').css('overflow-y', '');
                setTimeout(function() {
                    var titles = $('.mention-title .action-color-hover');
                    if (titles.length > 0) {
                        titles.each(function() {
                            $(this).width($(this).parent().parent().prev().offset().left - $(this).offset().left);
                        });
                    }
                    searchInStream($('#doSearchInStream').val());
                }, 2000);
            });
            /*$.post("/info/" + sstreamId + "/" + dateFrom + "/" + dateTo + "/0/10/" + language + "/" + tag + "/" + sentiment + messageActionFilter + '/' + type, function(data) {
             messageData = JSON.parse(data);
             if (messageData.newMessages > 0) {
             $('.main-section-nav .url-widget-link').first().find('span')[1].style.display = 'inline-block';
             $('.main-section-nav .url-widget-link').first().attr('tooltipData', messageData.newMessages + ' unread of ' + messageData.totalMessages + " messages<br>" + messageData.newLeads + ' unread of ' + messageData.totalLeads + " threads");
             if (messageData.newMessages <= 20)
             $('.main-section-nav .url-widget-link').first().find('span')[1].innerHTML = messageData.newMessages;
             else
             $('.main-section-nav .url-widget-link').first().find('span')[1].innerHTML = '20+';
             }
             else {
             $('.main-section-nav .url-widget-link').first().find('span')[1].innerHTML = '';
             $('.main-section-nav .url-widget-link').first().find('span')[1].style.display = 'none';
             $('.main-section-nav .url-widget-link').first().attr('tooltipData', "");
             }
             classificationData = messageData.classificationData;
             for (i = 1; i <= 4; i++) {
             var dt = classificationData[i];
             var htmlObject = $('.message-action-filter .action-link')[i - 1];
             var span = htmlObject.children[2];
             if (dt.new > 0) {
             span.style.display = 'inline-block';
             htmlObject.setAttribute('tooltipData', dt.new + ' unread of ' + dt.total + " messages");
             if (dt.new <= 20)
             span.innerHTML = dt.new;
             else
             span.innerHTML = '20+';
             }
             else {
             span.innerHTML = '';
             span.style.display = 'none';
             htmlObject.setAttribute('tooltipData', "");
             }
             }
             });*/
            dateFText = $.datepicker.parseDate('dd-mm-yy', dateFrom).toString().substring(4, 10);
            dateTText = $.datepicker.parseDate('dd-mm-yy', dateTo).toString().substring(4, 10);
            $('#selected_date').text(dateFText + ' - ' + dateTText);
            break;
        case "metrics":
            if (!metricsLoadCompleted) {
                LazyLoad.js(["/JS/Desktop/raphael-min.js", "/JS/Desktop/graphSupporter.js", "/Libs/highchart/js/highcharts.js"], function(d) {
                    loadMetrics();
                    metricsLoadCompleted = true;
                });
            }
            else
                loadMetrics();
            $('.list-viewport').animate({'opacity': 0.4}, 100);
            break;
            break;
        case "activity":
            break;
        case "compare":
            dateFText = $.datepicker.parseDate('dd-mm-yy', dateFrom).toString().substring(4, 10);
            dateTText = $.datepicker.parseDate('dd-mm-yy', dateTo).toString().substring(4, 10);
            $('#selected_date').text(dateFText + ' - ' + dateTText);
            loadComparison();
            break;
        case "engagement":
            dateFText = $.datepicker.parseDate('dd-mm-yy', dateFrom).toString().substring(4, 10);
            dateTText = $.datepicker.parseDate('dd-mm-yy', dateTo).toString().substring(4, 10);
            $('#selected_date').text(dateFText + ' - ' + dateTText);
            loadEngagement();
            break;
        case "sentiment":
            page = 1;
            $('.list-viewport').animate({'opacity': 0}, 100);
            $('.background-loading').animate({'opacity': 1}, 100);
            var undefinedFilter = '';
            if (window.location.href.split('#')[1].split('/')[3] !== undefined) {
                undefinedFilter = 'undefined';
            }

            if (window.location.href.split('#')[1].split('/')[2] !== undefined)
                threadId = window.location.href.split('#')[1].split('/')[2];
            else
                threadId = '';

            lastSeenPos = 0;
            pause = true;
            noMoreMessage = false;
            if (curRequest !== undefined)
                curRequest.abort();
            $('.list-viewport ul.widget-signals').html('');
            curRequest = loadpSentimentStream(sstreamId, dateFrom, dateTo, 0, streamEntryEachPage, language, tag, sentiment, '', type, source, function(text) {
                if ($('.background-loading').css('opacity') == 1) {
                    $('.background-loading').animate({'opacity': 0}, 100);
                    $('.list-viewport').animate({'opacity': 1}, 500);
                }
                var splitText = ' |||||| ';
                var newPos = text.indexOf(splitText, lastSeenPos + 1);
                if (text == 'Your query has no result! Try again!') {
                    showMessage('No more messages to show. Please try again later...');
                    noMoreMessage = true;
                }
                while (newPos !== -1) {
                    var element = '';
                    if (lastSeenPos > 0)
                        element = text.substring(lastSeenPos + splitText.length, newPos);
                    else
                        element = text.substring(lastSeenPos, newPos);
                    //console.log(element);
                    $('.list-viewport ul.widget-signals').append(element.replace(/\|\|\|\|\|\|/g, ''));
                    lastSeenPos = newPos;
                    newPos = text.indexOf(' |||||| ', lastSeenPos + 1);
                }
                $('.mention-text:not(.url-parsed), .main-reply-content:not(.url-parsed)').each(function() {
                    $(this).html(parseURL($(this).html()));
                    $(this).addClass("url-parsed");
                    $(this).attr('text', $(this).html());
                });
                $('.view-thread .unassigned').each(function() {
                    var undefinedFilter = '';
                    var streamId = window.location.href.split('#')[1].split('/')[1];
                    var url = '/#sentiment/' + streamId + '/' + $(this).parent().attr('threadid');
                    if (window.location.href.split('#')[1].split('/')[3] !== undefined) {
                        url += '/u';
                    }
                    $(this).attr('href', url);
                    $(this).removeClass('unassigned');
                });
            }, function(data) {
                if ($('.background-loading').css('opacity') == 1) {
                    $('.background-loading').animate({'opacity': 0}, 100);
                    $('.list-viewport').animate({'opacity': 1}, 500);
                }
                //console.log(data);
                if (data == 'Your query has no result! Try again!') {
                    showMessage('No more messages to show. Please try again later...');
                    noMoreMessage = true;
                }
                var splitText = ' |||||| ';
                var newPos = data.indexOf(splitText, lastSeenPos + 1);
                while (newPos !== -1) {
                    var element = '';
                    if (lastSeenPos > 0)
                        element = data.substring(lastSeenPos + splitText.length, newPos);
                    else
                        element = data.substring(lastSeenPos, newPos);
                    //console.log(element);
                    $('.list-viewport ul.widget-signals').append(element.replace(/\|\|\|\|\|\|/g, ''));
                    lastSeenPos = newPos;
                    newPos = data.indexOf(' |||||| ', lastSeenPos + 1);
                }
                pause = false;
                if ($('.list-viewport ul.widget-signals').length == 0)
                    $('.list-viewport').html('<ul class="mozaic-widget list mozaic-initialized widget-signals"></ul><div class="loading" style="width: 1026px; height: 0;"><div class="loading-percent" style="width: 0%;"></div><h3>Loading...</h3></div><style>.loading-percent {width: 0%;background-color: #008000;height: 2px;-webkit-transition: all 0.3s ease-in-out;}.loading {text-align: center;position: fixed;bottom: 0px;z-index: 20000;width: 100%;height: 0%;-webkit-transition: all 0.1s ease-in-out;-moz-transition: all 0.1s ease-in-out;-o-transition: all 0.1s ease-in-out;transition: all 0.1s ease-in-out;}</style>');
                $('.mention-text:not(.url-parsed), .main-reply-content:not(.url-parsed)').each(function() {
                    $(this).html(parseURL($(this).html()));
                    $(this).addClass("url-parsed");
                    $(this).attr('text', $(this).html());
                });

                setTimeout(function() {
                    var titles = $('.mention-title .action-color-hover');
                    if (titles.length > 0) {
                        titles.each(function() {
                            $(this).width($(this).parent().parent().prev().offset().left - $(this).offset().left);
                        });
                    }
                    searchInStream($('#doSearchInStream').val());
                }, 2000);
            });
            /*curRequest = $.post("/loadSentimentStream/" + sstreamId + "/" + dateFrom + "/" + dateTo + "/0/" + length + "/" + language + "/" + tag + "/" + sentiment + '/' + type + '/' + source + '?undefined=' + undefinedFilter + "&threadId=" + threadId, function(data) {
             
             });*/
            dateFText = $.datepicker.parseDate('dd-mm-yy', dateFrom).toString().substring(4, 10);
            dateTText = $.datepicker.parseDate('dd-mm-yy', dateTo).toString().substring(4, 10);
            $('#selected_date').text(dateFText + ' - ' + dateTText);
            break;
        case 'monitoring':
            $('.list-viewport').animate({'opacity': 0}, 100);
            $('.background-loading').animate({'opacity': 1}, 100);
            switch (window.location.href.split('#')[1].split('/')[1]) {
                case "month":
                    loadMonitoring(1);
                    $('li.active-section').removeClass('active-section');
                    $('.main-section-nav li:first').next().addClass('active-section');
                    break;
                case "lastupdate":
                    loadMonitoring(2);
                    $('li.active-section').removeClass('active-section');
                    $('.main-section-nav li:last').addClass('active-section');
                    break;
                default:
                    loadMonitoring(0);
                    $('li.active-section').removeClass('active-section');
                    $('.main-section-nav li:first').addClass('active-section');
                    break;
            }
            break;
        default:
            break;
    }
    $('.list-viewport').scrollTop(0);

}
var parent;
$(document).on('click', '.filter-button', function(e) {
    if ($(this).parent().hasClass("radio-options-sentiment"))
        if ($(this).hasClass('selected')) {
            $(this).removeClass('selected');
            return;
        }
        else {
            $(this).parent().children('.selected').removeClass('selected');
            $(this).addClass('selected');
            return;
        }
    $(this).parent().addClass('opened');
    $(this).parent().find('table').css('display', '');
    filterType = $(this).find('span').attr('id');
    parent = $(this).children('a');
    ids = parent.attr('data-value').split(',');
    $(this).next().find('.filter-container-list li').each(function(d) {
        if (ids.indexOf($(this).attr('data-value')) !== -1)
            $(this).addClass('selected');
        else
            $(this).removeClass('selected');
    });
});
$(document).on('click', '#account-tab a', function(e) {

});
$(document).on('click', 'a.url-widget-link', function(e) {
    $('#analytics-link-widget li.active-section').removeClass('active-section');
    noMoreMessage = false;
    pause = false;
    $('#controller-container').animate({'opacity': 0}, 100);
    $('.background-loading').animate({'opacity': 1}, 100);
    param = $(this).attr('href').split('#')[1].split('/')[0];
    if ($(this).attr('href').split('#')[1].split('/').length > 1)
        sstreamId = "/" + $(this).attr('href').split('#')[1].split('/')[1];
    else
        sstreamId = '';
    history.pushState({page: 1}, param, "#" + param + sstreamId);
    view = param;
    if (dateFrom == undefined)
        dateFrom = $('#from').datepicker().val();
    if (dateTo == undefined)
        dateTo = $('#to').datepicker().val();
    filter = $(this).parents('.opened').attr('id');
    $('ul.main-section-nav>.active-section').removeClass('active-section');
    $(this).parents('li').first().addClass('active-section');
    if ($('li.active-section').find('span').eq(0).text() === 'Mentions') {
        $('li.search-tab.in-stream').removeClass('hide');
    } else {
        $('li.search-tab.in-stream').addClass('hide');
    }
    if ($(this).parent().attr('id') == 'mentions-link-widget') {
        $(this).next().find('li.active-section').removeClass('active-section');
    }
    if ($('#stage q').html() == 'ON') {
        if ($(this).parent().attr('id') != 'mentions-link-widget') {
            if ($(document.body).hasClass('preview'))
                $(document.body).removeClass('preview');
            hidePreview();
        }
        else {
            if (!$(document.body).hasClass('preview'))
                $(document.body).addClass('preview');
            preview();
        }
    }
    if (sstreamId == undefined)
        sstreamId = '';

    loadMain(param, sstreamId);
});

$(document).on('click', '.settings-menu li', function(e) {
    $(this).parent('ul').children().removeAttr('class');
    $(this).attr('class', 'active-section');
    if ($(this).attr('id') == 'tags-tab') {
        var pl = new SOAPClientParameters();
        pl.add('groupId', 0);
        SOAPClient.invoke("/m/", "listTag", pl, true, listtag_callback);
    }
});

$(document).on('click', '.settings-menu a', function(e) {
    param = $(this).attr('href').split('#')[1];
    history.pushState({page: 1}, param, "#" + param);
    /*var viewportHTML = '';
     $.post("/" + param + "/viewport/", function(data) {
     viewportHTML = data;
     });*/
    if (typeof curRequest != 'undefined')
        curRequest.abort();
    curRequest = $.post("/" + param + "/mainview/", function(mainViewHTML) {
        hideloading();
        //loadViewport(viewportHTML);
        loadMainView(mainViewHTML);
        action = param.split('/')[1];
        switch (action) {
            case "account":
                $('body').removeClass('body-light');
                document.title = 'Account settings';
                break;
            case "notifications":
                $('body').removeClass('body-light');
                document.title = 'Notification settings';
                break;
            case "subscription":
                $('body').removeClass('body-light');
                document.title = 'Email settings';
                break;
            case "folders":
                currentFolder = 0;
                $('body').addClass('body-light');
                var pl = new SOAPClientParameters();
                SOAPClient.invoke("/m/", "getFolder", pl, true, getfolder_callback);
                pl.add('folderid', 0);
                SOAPClient.invoke("/m/", "listStream", pl, true, liststream_callback);
                document.title = 'Folders & Streams';
                break;
            case "groups":
                $('body').addClass('body-light');
                var pl = new SOAPClientParameters();
                SOAPClient.invoke("/m/", "getUser", pl, true, getuser_callback);
                document.title = 'Invite Users';
                break;
            case "tags":
                $('body').addClass('body-light');
                var pl = new SOAPClientParameters();
                SOAPClient.invoke("/m/", "getGroups", pl, true, function(r) {
                    groups = JSON.parse(r);
                    renderGroup();
                });
                $('.add_tag').last().css('display', 'none');
                document.title = 'Tags settings';
                break;
            case 'connected-accounts':
                $('body').addClass('body-light');
                var pl = new SOAPClientParameters();
                SOAPClient.invoke("/m/", "getAccounts", pl, true, getaccounts_callback);
                document.title = 'Social Accounts settings';
                break;
            default:
                $('body').addClass('body-light');
                document.title = 'buzzPulse settings';
                break;
        }
        $('#action-menu-content').attr('class', 'action-nav');
    });
});
function getuser_callback(r) {
    if (r["userid"] != undefined) {
        var userid = r["userid"].split(';');
        var username = r["username"].split(';');
        var usermail = r["usermail"].split(';');
        var lastlogin = r["lastlogin"].split(';');
        var avatar = r['avatar'].split(';');
        var html = '';
        for (i = 0; i < userid.length - 1; i++) {
            var li = '<li class="mozaic-widget item-71727 group-tab widget-user_item" email="' + usermail[i] + '">' +
                    '<a class="expand-folder" href="#" data-id="71727">' +
                    '<div class="user-image-holder holder-Contributor"><div class="user-type-icon"><i class="icon-contributor"></i><i class="icon-contributor user-back-icon"></i></div><img class="group-tab-user-img" src="http://www.gravatar.com/avatar/' + avatar[i] + '"></div>' +
                    '<span class="group-tab-user-name ">' + username[i] + '<em>&nbsp;(YOU)</em></span>' +
                    '<span class="group-tab-user-stats">Contributor</span>' +
                    '<span class="group-tab-user-stats user-stats-hover">Last login: ' + lastlogin[i] + '</span>' +
                    '</a>' +
                    '<div id="user-' + userid[i] + '" class="buttons-container">' +
                    '<div class="btn-holder edit-button"><a class="edit-user btn btn-small edit-button" data-id="71727"><i class="icon-edit"></i><span>Edit</span></a></div>' +
                    '<div id="delete_user" class="btn-holder delete-button"><a class="insert-delete-form delete-user btn btn-small delete-button" data-id="71727"><i class="icon-delete-folder"></i><span>Delete</span></a></div>' +
                    '</div>';
            html = html + li;
        }
        $('div.widget-user_transient_list').html(html);
    } else {
        $('div.widget-user_transient_list').empty();
    }
}
var currentFolder = 0;
var folders;
function getfolder_callback(r) {
    folders = r;
    renderFolder();
}

function renderFolder() {
    r = folders;
    if (r["folderid"] != undefined) {
        var folderid = r["folderid"].split(';');
        var foldername = r["foldername"].split(';');
        var parentid = r["parentid"].split(';');
        var parent = 0;
        for (i = 0; i < folderid.length; i++) {
            if (folderid[i] == currentFolder) {
                parent = parentid[i] == '' ? 0 : parentid[i];
            }
        }
        var html = '';
        if (currentFolder > 0) {
            var html = '<li data-id="' + parent + '" class="mozaic-widget folder-tab widget-folder_item">' +
                    '<a id="folder-tab" class="expand-folder">' +
                    '<i class="icon-folder"></i>' +
                    '<span>..</span>' +
                    '</a></li>';
        }
        for (i = 0; i < folderid.length - 1; i++) {
            if (parentid[i] == currentFolder) {
                var li = '<li data-id="' + folderid[i] + '" class="mozaic-widget folder-tab widget-folder_item">' +
                        '<a id="folder-tab" class="expand-folder">' +
                        '<i class="icon-folder"></i>' +
                        '<span>' + foldername[i] + '</span></a><a class="edit-folder" style="display: none; background-color: transparent!important;"><input id="foldername" name="foldername" placeholder="Your Folder" type="text" style="width: 145px;"> <input class="btn btn-red" id="btn-save" type="submit" value="Save">' +
                        '</a>\
                        <div class="buttons-container small"><div class="btn-holder edit-button"><a folderid="' + folderid[i] + '" data-context="market_terms" data-type="keyword" class="edit-button btn btn-small" style="position: initial;"><i class="icon-edit"></i><span>Edit</span></a></div></div></li>';
                html = html + li;
            }
        }
        $('ul#folderlist').html(html);
    } else {
        $('ul#folderlist').empty();
    }
    $.post('folder', function(data) {
        $('.widget-directory_list').first().html(data);
        navigateFolder();
    });
    $.post("/ajax/addStreamS3", function(data) {
        addStreamS3 = data;
    });
}

function hasChild(folderId) {
    if (folders["parentid"].indexOf(folderId) == -1)
        return false;
    return true;
}

$(document).on('click', '.widget-folder_settings #folder-tab.expand-folder:not(.folder-fade)', function(e) {
    var folderid = $(this).parent().attr('data-id');
    if ($(this).children('span').html() != '..' && $(this).children('span').html() != 'All Streams') {
        if ($('#all-folders').parent().attr('data-id') == 0) {
            currentFolder = folderid;
            $('#all-folders').attr('parent-name', $(this).children('span').html());
            $('#all-folders').parent().attr('data-id', folderid);
            renderFolder();
            $('#all-folders').click();
        }
        $(this).parent().parent().parent().parent().children('.folder-tab').children('a').attr('class', 'expand-folder all_folders');
        $(this).parent().parent().children('li').children('a').not('.folder-fade').not('.edit-folder').attr('class', 'expand-folder');
        $(this).attr('class', 'expand-folder expanded-folder');
        $('#stream-title').text($(this).children('span').text().split('(')[0].trim());
        var pl = new SOAPClientParameters();
        pl.add('folderid', folderid);
        SOAPClient.invoke("/m/", "listStream", pl, true, liststream_callback);
    }
    else {
        $('#all-folders').attr('parent-name', '');
        $('#all-folders').parent().attr('data-id', 0);
        currentFolder = folderid;
        renderFolder();
        $('#all-folders').click();
    }
});

function liststream_callback(r) {
    if (r["streamid"] !== "undefined") {
        var streamid = r["streamid"].split(';');
        var streamname = r["streamname"].split(';');
        var sfolderid = r["folderid"].split(';');
        var html = '';
        for (i = 0; i < streamid.length; i++) {
            var li = '<li class="mozaic-widget item-1000031974 folder-tab first widget-stream_item">' +
                    '<div class="social-profile-disconnected">' +
                    '<a class="expand-folder type-keyword" href="#stream/' + Base64.encode(streamid[i]) + '">' +
                    '<i class="icon-stream-type icon-stream-market_terms-small"></i><span>' + streamname[i] + '</span>' +
                    '</a>' +
                    '<div class="buttons-container small">' +
                    /*'<div class="btn-holder edit-button">' +
                     '<a data-id="' + streamid[i] + '" folderid="' + parseInt(sfolderid[i]) + '" data-context="market_terms" data-type="keyword" class="edit-button btn btn-small">' +
                     '<i class="icon-edit"></i><span>Edit</span>' +
                     '</a>' +
                     '</div>' +
                     '<div class="btn-holder delete-button">' +
                     '<a data-id="' + streamid[i] + '" folderid="' + parseInt(sfolderid[i]) + '" data-type="keyword" class="insert-delete-form delete-button btn btn-small">' +
                     '<i class="icon-delete-folder"></i><span>Delete</span>' +
                     '</a>' +
                     '</div>' +
                     '</div>' +*/
                    '</div>' +
                    '</li>';
            html = html + li;
        }
        $('div.mozaic-widget.widget-list ul').html(html);
    }
    else {
        $('div.mozaic-widget.widget-list ul').empty();
    }
}

$(document).on('click', '.widget-directory_list expand-folder#all-folders', function(e) {
    $('#folderlist').children().children('a').not('.folder-fade').attr('class', 'expand-folder');
    $(this).attr('class', 'expand-folder all_folders expanded-folder');
    $('#stream-title').text($(this).attr('parent-name'));
    var pl = new SOAPClientParameters();
    pl.add('folderid', currentFolder);
    SOAPClient.invoke("/m/", "listStream", pl, true, liststream_callback);
});

$(document).on('click', '.select-stream-group button', function(e) {
    if ($('#folders-tab').attr('class') != undefined) {
        var pl = new SOAPClientParameters();
        SOAPClient.invoke("/m/", "getFolderType", pl, true, getfoldertype_callback);
    }
});
function getfoldertype_callback(r) {
    if (r["typeid"] != undefined) {
        var typeid = r["typeid"].split(';');
        var typename = r["typename"].split(';');
        var html = '';
        for (i = 0; i < typeid.length - 1; i++) {
            var li = '<li data-value="' + typename[i] + '-' + typeid[i] + '">' +
                    '<a>' +
                    '<i class="icon-stream-type icon-stream-' + typename[i].toLowerCase() + '-small"></i>' +
                    '<span>' + typename[i] + '</span>' +
                    '</a>' +
                    '</li>';
            html = html + li;
        }
        $('ul.dropdown-menu.pull-right').html(html);
    } else {
        $('ul.dropdown-menu.pull-right').empty();
    }
}

function addfolder_callback(r) {
    if (r == "true") {
        var pl = new SOAPClientParameters();
        SOAPClient.invoke("/m/", "getFolder", pl, true, getfolder_callback);
    }
}

$(document).on('click', '#delete_user a', function(e) {
    var pl = new SOAPClientParameters();
    pl.add('userid', $(this).parent().parent().attr('id').split('-')[1]);
    SOAPClient.invoke("/m/", "deleteUser", pl, true, deleteuser_callback);
});
function deleteuser_callback(r) {
    if (r == "true") {
        var pl = new SOAPClientParameters();
        SOAPClient.invoke("/m/", "getUser", pl, true, getuser_callback);
    }
}

$(document).on('submit', '.widget-search_stream_wizard form', function(e) {
    return false;
});
$(document).on('click', '.widget-add_folder button', function(e) {
    if ($('#addfolder').css('display') == 'block') {
        $('#addfolder').css('display', 'none');
    }
    else {
        $('#addfolder').css('display', 'block');
    }
    return false;
});
$(document).on('click', '#addfolder .btn', function(e) {
    folderName = $('#addfolder #foldername').val();
    if (folderName != '') {
        parentId = $('.main-section-nav .expanded-folder').parent().attr('data-id');
        var pl = new SOAPClientParameters();
        pl.add('folderName', folderName);
        pl.add('parentId', currentFolder);
        SOAPClient.invoke("/m/", "addFolder", pl, true, addfolder_callback);
        $('#addfolder #foldername').val('');
        $('#addfolder').css('display', 'none');
    }
});

function deletetag_callback(r) {
    if (r == "true") {
        var pl = new SOAPClientParameters();
        SOAPClient.invoke("/m/", "getTag", pl, true, getTag_callback);
    }
}
var params = '';
if (params = window.location.href.split("#").length > 1)
    params = window.location.href.split("#")[1].split('/')[0];
if (params == 'stream')
    updateTimer = setInterval("updateStream()", 30000);
lastUpdate = new Date();
function updateStream() {
    return;
    var params = '';
    if (params = window.location.href.split("#").length > 1)
        params = window.location.href.split("#")[1].split('/')[0];
    if (params == 'stream') {
        sstreamId = window.location.href.split("#")[1].split('/')[1];
        if (sstreamId === undefined)
            sstreamId = Base64.encode('1');
        curRequest = $.post("newstream/" + sstreamId + "/" + formatDate(lastUpdate), function(data) {
            if (data.length > 37) {
                html = $('ul.widget-signals').html();
                link = $(data).find('.mention-title a').attr('href');
                if ($('ul.widget-signals').html().indexOf(link) == -1) {
                    $('ul.widget-signals').prepend(data);
                }
            }
            lastUpdate = new Date();
        });
    }
}

function formatDate(date) {
    day = pad(date.getDate(), 2);
    month = pad(date.getMonth() + 1, 2);
    year = date.getFullYear();
    hours = pad(date.getHours(), 2);
    minutes = pad(date.getMinutes(), 2);
    seconds = pad(date.getSeconds(), 2);
    return day + '-' + month + '-' + year + ' ' + hours + ':' + minutes + ':' + seconds;
}

function pad(num, size) {
    var s = num + "";
    while (s.length < size)
        s = "0" + s;
    return s;
}

$(document).on('click', '.settings-stream-menu a', function(e) {
    switch ($(this).attr('class')) {
        case "edit-object":
            param = window.location.href.split('#')[1].split('/')[1];
            streamName = $('.stream-title span').html().trim();
            folderId = $(this).attr('folderid');
            streamId = $(this).attr('streamid');
            needToNavigate = true;
            getStream(Base64.decode(param));
            break;
        case 'delete-object':
            streamId = $(this).attr('streamid');
            var pl = new SOAPClientParameters();
            pl.add('streamId', streamId);
            SOAPClient.invoke("/m/", "deleteStream", pl, true, deleteStream_callback);
            break;
        default:
            break;
    }

    function deleteStream_callback() {
        navigateURL("Home");
        $.post('folder', function(data) {
            $('.widget-directory_list').first().html(data);
            navigateFolder();
        });
    }
});
$(document).on('click', '#step-0', function(e) {
    if ($('.modal-body').html() !== addStreamS1) {
        $('.modal-title').html("Add A New Stream");
        $('.modal-body').html(addStreamBC + addStreamS1);
    }
    $('.modal-backdrop').css('display', 'block');
    $('.modal-backdrop').addClass('in');
    $('.modal-backdrop').css('z-index', '9999');
    $('#modal').css('z-index', '10000');
    $('#modal').addClass("in");
    $('.modal-body').html(addStreamBC + addStreamS1);
    folderId = '';

    if (advancedQuery) {
        $('.advanced-query a').html('Basic query');
        $('#basic-query').hide();
        $('#advanced-query').show();
        $('#c1195_query').val(streamQuery.replace(/&amp;/g, '&').trim());
    }

    $('.modal-body .btn-red.commit').click(function(e) {
        if ($('.advanced-query a').html() == 'Advanced query') {
            query = new Array();
            query['all'] = $('#c1195_all').val();
            query['any'] = $('#c1195_any').val();
            query['none'] = $('#c1195_none').val();
            advancedQuery = false;
        }
        else {
            query = $('#c1195_query').val();
            advancedQuery = true;
        }
        loadStream(2);
    });

    if (!advancedQuery) {
        $('#c1195_all').val(query['all']);
        $('#c1195_any').val(query['any']);
        $('#c1195_none').val(query['none']);
    }
    else {
        $('.advanced-query a').html('Basic query');
        $('#basic-query').hide();
        $('#advanced-query').show();
        $('#c1195_none').val(query);
    }

});
$(document).on('click', '#step-1', function(e) {
    loadStream(2);
});
function getStream(streamId) {
    var pl = new SOAPClientParameters();
    pl.add('streamId', streamId);
    SOAPClient.invoke("/m/", "getStream", pl, true, getStream_callback);
}

function getStream_callback(r) {
    stream = r;
    editStream();
}

$(document).on('click', '.streams .edit-button', function(e) {
    streamId = $(this).children('a').attr('data-id');
    folderId = $(this).children('a').attr('folderid');
    streamName = $(this).parents('li').find('span').first().html();
    needToNavigate = false;
    if (streamId != undefined)
        getStream(streamId);
});
function editStream() {
    if ($('.modal-body').html() !== addStreamS1) {
        $('.modal-title').html("Edit Stream " + streamName);
        $('.modal-body').html(addStreamBC + addStreamS1);
    }
    $('.modal-backdrop').css('display', 'block');
    $('.modal-backdrop').addClass('in');
    $('.modal-backdrop').css('z-index', '9999');
    $('#modal').show();
    $('#modal').css('z-index', '10000');
    $('#modal').addClass("in");
    $('.modal-body').html(addStreamBC + addStreamS1);
    if (stream.externalSources != null)
        streamSources = stream.externalSources.split(';');
    $('.modal-body .btn-red.commit').click(function(e) {
        if ($('.advanced-query a').html() == 'Advanced query') {
            query = new Array();
            query['all'] = $('#c1195_all').val();
            query['any'] = $('#c1195_any').val();
            query['none'] = $('#c1195_none').val();
            advancedQuery = false;
        }
        else {
            query = $('#c1195_query').val();
            advancedQuery = true;
        }
        loadStream(2);
    });
    streamQuery = stream.query;
    if (streamQuery.indexOf('\t') == -1) {
        streamQueryArr = streamQuery.split(") &");
        queryAll = '';
        queryNone = '';
        queryAny = '';
        if (streamQueryArr.length == 2) {
            if (streamQuery.indexOf('- (') == -1)
            {
                //In case 1, 2 no problem
                streamQueryArr[0] = streamQueryArr[0];
                streamQueryArr[2] = streamQueryArr[1];
                streamQueryArr[1] = undefined;
            }
            if (streamQuery.indexOf('- (') == 0) {
                streamQueryArr[2] = streamQueryArr[1];
                streamQueryArr[1] = streamQueryArr[0];
                streamQueryArr[0] = undefined;
            }
        }
        if (streamQueryArr.length == 1) {
            if (streamQuery.indexOf('- (') != -1) {
                //None
                streamQueryArr[1] = streamQueryArr[0];
                streamQueryArr[0] = undefined;
                streamQueryArr[2] = undefined;
            } else if (streamQuery.indexOf('\n') != -1) {
                //Any
                streamQueryArr[2] = streamQueryArr[0];
                streamQueryArr[0] = undefined;
                streamQueryArr[1] = undefined;
            }
        }

        if (streamQueryArr[0] != undefined)
            queryAll = escape(streamQueryArr[0]).trim().replace(/%20/g, ' ').replace(/%22/g, '').replace(/ %26/g, ',').replace(/%28/g, '').replace(/%29/g, '').trim();
        if (streamQueryArr[1] != undefined)
            queryNone = escape(streamQueryArr[1].trim().replace(/- \(/, '').replace(/\)/, '').trim()).replace(/%20/g, ' ').replace(/%22/g, '').replace(/ %7C /g, ',').replace(/ %26/g, ',').trim();
        if (streamQueryArr[2] != undefined)
            queryAny = escape(streamQueryArr[2].trim().replace(/"/g, '').replace(/- \(/, '').replace(/\)/, '').replace(/\(/, '').trim()).replace(/%20%7C%20/g, ', ').replace(/%20/g, ' ');
        $('#c1195_all').val(unescape(queryAll));
        $('#c1195_any').val(unescape(queryAny));
        $('#c1195_none').val(unescape(queryNone));
    }
    if (streamQuery.indexOf('\t') != -1) {
        $('.advanced-query a').html('Basic query');
        $('#basic-query').hide();
        $('#advanced-query').show();
        $('#c1195_query').val(streamQuery.trim());
    }
}

var objDel;
$(document).on('click', '.folders-content .delete-button', function(e) {
    streamId = $(this).children('a').attr('data-id');
    objDel = $(this).parents('li');
    if (streamId != undefined) {
        var pl = new SOAPClientParameters();
        pl.add('streamId', streamId);
        SOAPClient.invoke("/m/", "deleteStream", pl, true, deleteStreamS_callback);
    }
});
function deleteStreamS_callback(r) {
    objDel.remove();
    $.post('folder', function(data) {
        $('.widget-directory_list').first().html(data);
        navigateFolder();
    });
}

$(document).on('click', '.add-link', function(e) {
    $(this).css('display', 'none');
    $(this).next().css('display', '');
});

$(document).on('click', '#change-password', function(data) {
    $('#change-password-form').animate({'height': 223, 'opacity': 1}, 500);
    $('#info-form').animate({'height': 0, 'opacity': 0}, 500);
    $(this).attr('id', 'back-to-info');
    $(this).html('<i class="icon-back"></i>Back');
});
$(document).on('click', '#back-to-info', function(data) {
    $('#change-password-form').animate({'height': 0, 'opacity': 0}, 500);
    $('#info-form').animate({'height': 244, 'opacity': 1}, 500);
    $(this).attr('id', 'change-password');
    $(this).html('<i class="icon-lock"></i>Change password');
});
$(document).on('click', '.settings-account-container .btn-red.commit', function(e) {
    $('.error').css('color', 'red');
    changeButton = $('.change-password a').last();
    if (changeButton.attr('id') != 'change-password') {
        //change password
        oldPassword = $('#c2021_old_password').val();
        newPassword = $('#c2021_new_password').val();
        confirmPassword = $('#c2021_confirm_password').val();
        if (newPassword != confirmPassword)
            $('.error').html("Error: Password does not match! Please check it!");
        else {
            tagName = $(this).prev().val();
            var pl = new SOAPClientParameters();
            pl.add("oldPassword", hex_md5(oldPassword));
            pl.add("newPassword", hex_md5(newPassword));
            SOAPClient.invoke("/m/", "changePassword", pl, true, changePassword_callback);
        }
    }
    else {
        //change info
        firstName = $('#c2021_first_name').val();
        lastName = $('#c2021_last_name').val();
        if (firstName != '' && lastName != '') {
            var pl = new SOAPClientParameters();
            name = firstName + ' ' + lastName;
            pl.add("name", name);
            SOAPClient.invoke("/m/", "changeName", pl, true, changeName_callback);
        }
        else {
            $('.error').html("You cannot leave your name empty...")
        }
    }
});
function changePassword_callback(r) {
    if (r == "succeed") {
        window.location = '/logout';
    }
    else {
        $('.error').html("Error: " + r);
    }
}

function changeName_callback(r) {
    if (r == "succeed") {
        $('.error').css('color', 'green');
        $('.error').html("Action performed successfully");
    }
    else {
        $('.error').html("Something wrong :(");
    }
}

function loadMain(param, sstreamId) {
    $('.main-loading-percent').height(2);
    function getXMLHttpRequest() {
        if (window.XMLHttpRequest) {
            return new window.XMLHttpRequest;
        } else {
            try {
                return new ActiveXObject("MSXML2.XMLHTTP");
            } catch (ex) {
                return null;
            }
        }
    }

    function handler() {
        if (oReq.readyState == 4 /* complete */) {
            if (oReq.status == 200) {
                loadMainCompleted(param, oReq.responseText);
            }
        }
    }
    var oReq = getXMLHttpRequest();
    if (typeof curRequest !== 'undefined')
        curRequest.abort();
    curRequest = oReq;

    if (oReq != null) {
        oReq.open("GET", "/" + param + sstreamId + "/mainview/", true);
        oReq.onreadystatechange = handler;
        oReq.onprogress = progress;
        oReq.send();
    } else {
        window.alert("AJAX (XMLHTTP) not supported.");
    }

    function progress() {
        length = oReq.getResponseHeader('Content-length');
        //console.log(oReq.responseText);
        curlength = oReq.responseText.length;
        ppercent = curlength / length * 100;
        barpercent += Math.round((ppercent - lpercentM) * 40 / 100);
        bar.style.width = barpercent + '%';
        $('.main-loading-percent').css('width', Math.round(ppercent) + '%');
        lpercentM = ppercent;
    }
}

function loadMainCompleted(param, mainViewHTML) {
    params = param.split('/');
    param = String(params[0].toString()).toLowerCase();
    $('body').removeClass('body-light');
    switch (param) {
        case "home":
            $('#home-fix-style').html('.fixed-fluid { margin-left: 70px; z-index: 2002; }' +
                    '#action-menu-content { width: 190px; background: rgba(235,236,238,0.9); }');
            $('.selected-tab').removeClass("selected-tab");
            $('.dashboard-tab a').addClass("selected-tab");
            document.title = 'Welcome to buzzPulse';
            break;
        case "alert":
            $('.selected-tab').removeClass("selected-tab");
            $('.inbox-tab a').addClass("selected-tab");
            document.title = 'Alerts';
            break;
        case "stream":
            $('.selected-tab').removeClass("selected-tab");
            $('.inbox-tab a').addClass("selected-tab");
            document.title = 'Stream for ' + $('.stream-title span').html();
            break;
        case "activity":
            $('.selected-tab').removeClass("selected-tab");
            $('.activity-tab a').addClass("selected-tab");
            document.title = 'Activity';
            break;
        case "reports":
            $('.selected-tab').removeClass("selected-tab");
            $('.reports-tab a').addClass("selected-tab");
            break;
        case "metrics":
            $('#home-fix-style').html('');
            $('.selected-tab').removeClass("selected-tab");
            $('.inbox-tab a').addClass("selected-tab");
            document.title = 'Metrics for ' + $('.stream-title span').html();
            if (!metricsLoadCompleted) {
                LazyLoad.js(["/JS/Desktop/raphael-min.js", "/JS/Desktop/graphSupporter.js", "/Libs/highchart/js/highcharts.js"], function(d) {
                    loadMetrics();
                    metricsLoadCompleted = true;
                });
            }
            else
                loadMetrics();
            break;
        case "compare":
            $('#home-fix-style').html('');
            document.title = 'Comparison for ' + $('.stream-title span').html();
            break;
        case "engagement":
            $('#home-fix-style').html('');
            document.title = 'Engagement for ' + $('.stream-title span').html();
            break;
        case "sentiment":
            $('#home-fix-style').html('');
            document.title = 'Sentiment Scoring for ' + $('.stream-title span').html();
            break;
        case "settings":
            document.title = 'buzzPulse settings';
            break;
        case "monitoring":
            $('#home-fix-style').html('');
            document.title = 'Monitoring Team KPI';
            applyFilter();
            break;
        default:
            $('#home-fix-style').html('.fixed-fluid { margin-left: 70px; z-index: 2002; }' +
                    '#action-menu-content { width: 190px; background: rgba(235,236,238,0.9); }');
            $('.selected-tab').removeClass("selected-tab");
            $('.dashboard-tab a').addClass("selected-tab");
            document.title = 'Welcome to buzzPulse';
            break;
    }
    loadMainView(mainViewHTML);
    if ($('.list-viewport ul.widget-list').text().trim() === '' && param === 'activity') {
        noMoreMessage = true;
        $('.list-viewport').css('overflow-y', 'hidden');
        var ul = $('.list-viewport ul.widget-list');
        ul.height($(window).height());
        ul.html('<div class="no-result" style="width: 300px;font-size: 13pt;text-align: center;padding: 30px 10px;vertical-align: middle;margin: 150px auto;background: #FFF;border: 1px solid #BBB;border-radius: 2px;box-shadow: 1px 1px 1px #BBB;"><h1 style="line-height: 70pt; font-size: 49pt;-webkit-transform: rotate(90deg);-moz-transform: rotate(90deg);-o-transform: rotate(90deg);transform: rotate(90deg);">:-(</h1><h3>Sorry!</h3>There\'s no data yet.<br>Please check back later...</div>');
        $('.background-loading').animate({'opacity': 0}, 100);
        $('.list-viewport').animate({'opacity': 1}, 500);
    }
    if ($('.compare-stream-list').length > 0) {
        $('.compare-stream-list').css('width', $('.main-content').width() + 20 + 'px');
        $('.compare-stream-list select').css('width', $('.stream-block').first().width() - 40 + 'px');
    }
    $('.main-loading-percent').css('width', '100%');
    var ttimer = setTimeout(function() {
        $('.main-loading-percent').height(0);
        tmr = setTimeout(function() {
            $('.main-loading-percent').width(0);
            clearInterval(tmr);
        }, 500);
        clearInterval(ttimer);
    }, 500);

    if (param == "settings" && sstreamId != undefined) {
        action = sstreamId.split('/')[1];
        $('#account-tab').removeAttr('class');
        $('#' + action + '-tab').addClass('active-section');
        switch (action) {
            case "account":
                $('body').removeClass('body-light');
                document.title = 'Account settings';
                break;
            case "notifications":
                $('body').removeClass('body-light');
                document.title = 'Notification settings';
                break;
            case "subscription":
                $('body').removeClass('body-light');
                document.title = 'Subscription';
                break;
            case "folders":
                $('body').addClass('body-light');
                var pl = new SOAPClientParameters();
                SOAPClient.invoke("/m/", "getFolder", pl, true, getfolder_callback);
                pl.add('folderid', 0);
                SOAPClient.invoke("/m/", "listStream", pl, true, liststream_callback);
                document.title = 'Folders & Streams';
                break;
            case "groups":
                $('body').addClass('body-light');
                var pl = new SOAPClientParameters();
                SOAPClient.invoke("/m/", "getUser", pl, true, getuser_callback);
                document.title = 'Invite Users';
                break;
            case "tags":
                $('body').addClass('body-light');
                var pl = new SOAPClientParameters();
                SOAPClient.invoke("/m/", "getTag", pl, true, getTag_callback);
                document.title = 'Tags settings';
                break;
            case 'connected-accounts':
                $('body').addClass('body-light');
            default:
                $('body').addClass('body-light');
                break;
        }
    }
    documentReady = true;
}

function loadViewPort(param, sstreamId) {
    function getXMLHttpRequest() {
        if (window.XMLHttpRequest) {
            return new window.XMLHttpRequest;
        } else {
            try {
                return new ActiveXObject("MSXML2.XMLHTTP");
            } catch (ex) {
                return null;
            }
        }
    }

    function handler() {
        if (oReq.readyState == 4 /* complete */) {
            if (oReq.status == 200) {
                loadViewPortCompleted(param, sstreamId, oReq.responseText);
            }
        }
    }

    var oReq = getXMLHttpRequest();

    if (oReq != null) {
        oReq.open("GET", "/" + param + sstreamId + "/viewport/", true);
        oReq.onreadystatechange = handler;
        oReq.onprogress = progress;
        oReq.send();
    } else {
        window.alert("AJAX (XMLHTTP) not supported.");
    }

    function progress() {
        length = oReq.getResponseHeader('Content-length');
        curlength = oReq.responseText.length;
        //console.log(oReq.responseText);
        ppercent = curlength / length * 100;
        barpercent += Math.round((ppercent - lpercentV) * 26 / 100);
        bar.style.width = barpercent + '%';
        lpecentV = ppercent;
    }
}

function loadViewPortCompleted(param, sstreamId, viewportHTML) {
    loadMain(param, sstreamId);
    param = window.location.href.split('#')[1];
    params = param.split('/');
    loadViewport(viewportHTML);
    switch (params[0].toLowerCase()) {
        case "alert":
        case "stream":
        case "monitoring":
        case "activity":
        case "reports":
        case "metrics":
        case "engagement":
        case "sentiment":
        case "compare":
            $('#home-fix-style').html('');
            break;
        case "settings":
            $('#home-fix-style').html('');
            switch (params[1]) {
                case 'account':
                    $('#account-tab a').click();
                    break;
                case 'folders':
                    $('#folders-tab a').click();
                    break;
                case 'connected-accounts':
                    $('#social_profile-tab a').click();
                    break;
                case 'groups':
                    $('#groups-tab a').click();
                    break;
                case 'tags':
                    $('#tags-tab a').click();
                    break;
                case 'notifications':
                    $('#notifications-tab a').click();
                    break;
                case 'subscription':
                    $('#subscription-tab a').click();
                    break;
                default:
                    $('#account-tab a').click();
                    break;
            }
            break;
        case "home":
            $('#home-fix-style').html('.fixed-fluid { margin-left: 70px; z-index: 2002; }' +
                    '#action-menu-content { width: 190px; background: rgba(235,236,238,0.9); }');
            $(document.body).removeClass('preview');
        default:
            $('#home-fix-style').html('.fixed-fluid { margin-left: 70px; z-index: 2002; }' +
                    '#action-menu-content { width: 190px; background: rgba(235,236,238,0.9); }');
            $(document.body).removeClass('preview');
            break;
    }
}

var tempHTML = '';
var objccc;

$(document).on('mouseleave', 'ul.right-action-bar', function() {
    if (tempHTML != '' && objccc != undefined) {
        objccc.html(tempHTML);
    }
});

$(document).on('click', '.sentiment-item-list button', function(event) {
    tempHTML = $(this).parents('ul.right-action-bar').html();
    objccc = $(this).parents('ul.right-action-bar');
    $(this).parents('ul.right-action-bar').html('<li class="right-action-item sentiment-item-list">' +
            '<div class="sentiment">' +
            '<a class="set-filter select positive cursor-pointer" rel="tooltip" title="Show all positive mentions">' +
            '<i class="icon-positive"></i><span class="text-to-hide">positive</span>' +
            '</a>' +
            '</div>' +
            '</li>' +
            '<li class="right-action-item sentiment-item-list">' +
            '<div class="sentiment">' +
            '<a class="set-filter select negative cursor-pointer" rel="tooltip" title="Show all positive mentions">' +
            '<i class="icon-negative"></i><span class="text-to-hide">negative</span>' +
            '</a>' +
            '</div>' +
            '</li>' +
            '<li class="right-action-item sentiment-item-list">' +
            '<div class="sentiment">' +
            '<a class="set-filter select neutral cursor-pointer" rel="tooltip" title="Show all positive mentions">' +
            '<i class="icon-neutral"></i><span class="text-to-hide">neutral</span>' +
            '</a>' +
            '</div>' +
            '</li>');
    objccc.find('.sentiment').click(function() {
        var ul = $(this).parents('ul.right-action-bar');
        var messageId = ul.attr('messageid');
        var threadId = ul.attr('threadid');
        var type = ul.attr('type');
        var source = ul.attr('source');
        var score = 0;
        data = $(this).find('.text-to-hide').html();
        switch (data) {
            case "positive":
                score = 1;
                break;
            case "negative":
                score = -1;
                break;
            default:
                score = 0;
                break;
        }
        var pl = new SOAPClientParameters();
        pl.add('messageId', messageId);
        pl.add('threadId', threadId);
        pl.add('score', score);
        dateString = $(this).parents('ul.right-action-bar').attr('date');
        pl.add('dateCreated', dateString);
        tstreamId = Base64.decode(window.location.href.split('#')[1].split('/')[1]);
        pl.add('streamId', tstreamId);
        pl.add('type', type);
        pl.add('source', source);
        SOAPClient.invoke("/m/", "changeSentiment", pl, true, changeSentiment_callback);
        objccc.html(tempHTML);
        var sentimentColor = (score == 0) ? "#9bbb59" : (score > 0 ? "#4f81bd" : "#c0504d");
        objccc.find('.sentiment').find('i, a').css('background-color', sentimentColor);
        objccc.find('.sentiment').find('i').attr('class', 'icon-' + data);
        objccc.find('.sentiment').find('i').attr('class', 'icon-' + data);
        objccc.find('.sentiment').find('.text-to-hide').html(data);
        tempHTML = objccc.html();
    });
});

$(document).on('click', '.share-item-list button', function(event) {
    tempHTML = $(this).parents('ul.right-action-bar').html();
    objccc = $(this).parents('ul.right-action-bar');
    $(this).parents('ul.right-action-bar').html('<li class="right-action-item share-item-list">' +
            '<div class="share">' +
            '<a class="set-filter select positive cursor-pointer" rel="tooltip" title="Show message">' +
            '<i class="icon-email"></i><span class="text-to-hide">via email</span>' +
            '</a>' +
            '</div>' +
            '</li>' +
            '<li class="right-action-item sentiment-item-list">' +
            '<div class="sentiment">' +
            '<a class="set-filter select negative cursor-pointer" rel="tooltip" title="Show message">' +
            '<i class="icon-sms"></i><span class="text-to-hide">via sms</span>' +
            '</a>' +
            '</div>' +
            '</li>');
    objccc.find('.share').click(function() {
        messageId = $(this).parents('ul.right-action-bar').attr('messageid');
        var type = $(this).find('.text-to-hide').html();
        switch (type) {
            case "via email":
                var streamId = $(this).parents('div.mention-core').find('li.mention-action-button.retweet_dropdown').attr('streamId');
                var img = $(this).parents('div.mention-core').find('div.profile-img').children('img').attr('src');
                var time = $(this).parents('div.mention-core').find('p.mention-type.additional-timestamp.signals-additional-time').text();
                var threadTitle = $(this).parents('div.mention-core').find('a.action-color-hover').text();
                var icon = $(this).parents('div.mention-core').find('p.mention-short-url').children('img').attr('src');
                var source = $(this).parents('div.mention-core').find('a.action-color-active')[0].text;
                var streamTitle = $(this).parents('div.mention-core').find('a.action-color-active')[1].text;
                var text = $(this).parents('div.mention-core').find('div.mention-text.url-parsed').text();
                replyMail = '<div style="border: solid 1px #cecece;border-top: none;margin-left: 20px;margin-right: 20px;">';
                var data = $(this).parents('div.mention-right-wrapper').find('div.user-author-mention-actions.mention-top-bar');
                for (var i = 0; i < 5 && i <= data.length; i++) {
                    replyMail = replyMail + '<div style="min-height:auto;min-height:62px;padding-left: 20px;padding-right: 10px;">' +
                            '<div style="float: left;">' +
                            '<img style="width:32px;min-height:32px;border-radius:0;margin-top: 8px;margin-right: 8px;" src="' + data.eq(i).find('img').attr('src') + '"></div>' +
                            '<div style="float: left; max-width: 70%;">' +
                            '<p style="overflow:hidden;display:block;font-size: 14px !important;margin-top: 0px;margin-bottom: 0px;padding-top: 5px;padding-bottom: 5px;margin-right: 8px;">' +
                            '<strong style="color: #3B5998 !important;font-weight: bold;">' + data.eq(i).find('div.float-left.main-reply-content.url-parsed').children('p').children('strong').text() + '</strong>' +
                            '<span style="color: #333;  margin: 0 2px 0 0;  };">' + data.eq(i).find('div.float-left.main-reply-content.url-parsed').children('p').children('span').text() + '</span></p></div><div>' +
                            '<span style="line-height:22px;float: right;  font-size: 13px;">' + data.eq(i).find('div.float-right').children('span').text() + '</span></div>' +
                            '<div style="clear: right;  margin-top: -0.5em;float: right;"><div>' +
                            '<i style="background-image: url(' + '/Images/fb_icons.png);  background-repeat: no-repeat;  background-size: auto;  background-position: 0 0;  height: 14px;  width: 16px;  };"></i>' +
                            '<div>' + data.eq(i).find('div.thread-details').children('div').text() + '</div></div></div></div>';
                }
                replyMail = replyMail + '</div>';
                dataMail = img + ';' + time + ';' + threadTitle + ';' + icon + ';' + source + ';' + streamTitle + ';' + text;
                if ($('.modal-body').html() !== shareViaEmail) {
                    var title = 'Share via your email';
                    $('.modal-body').html(shareViaEmail);
                    $('.modal-title').html(title);
                    messageType = "share via email";
                }
                $('.modal-backdrop').css('display', 'block');
                $('#modal').css('width', '380px');
                $('#modal').css('margin-left', '-190px');
                $('.modal-backdrop').addClass('in');
                $('.modal-backdrop').css('z-index', '9999');
                $('#modal').css('z-index', '10000');
                $('#modal').addClass("in");
                html = $(this).parents('li.list-item').html();
                break;
            case "via sms":
                score = 1;
                break;
            default:
                score = -1;
                break;
        }
    });
});

function changeSentiment_callback(r) {
    /*if (r == 'failed')
     console.log(r);*/
}

$(document).on('mouseleave', '.widget-story_signal, ul.right-action-bar', function(event) {
    if (tempHTML != '' && objccc != undefined) {
        objccc.html(tempHTML);
    }
});

$(document).on('click', '.advanced-query a', function(event) {
    if ($(this).html() == 'Advanced query') {
        $(this).html('Basic query');
        $('#basic-query').hide();
        $('#advanced-query').show();
        query = new Array();
        query['all'] = $('#c1195_all').val();
        query['any'] = $('#c1195_any').val();
        query['none'] = $('#c1195_none').val();
        $('#c1195_query').val(createQuery(query).replace(/&amp;/g, '&').trim());
    }
    else {
        $(this).html('Advanced query');
        $('#advanced-query').hide();
        $('#basic-query').show();
        $('#c1195_all').val('');
        $('#c1195_any').val('');
        $('#c1195_none').val('');
    }
});

function createQuery(query) {
    andMark = '';
    streamQuery = '';
    if (query['all']) {
        keywords = query['all'].split(',');
        sQuery = "";
        for (i = 0; i < keywords.length; i++) {
            keywords[i] = keywords[i].trim();
            if (keywords[i].length != 0) {
                if (keywords[i].indexOf('-') != -1 || keywords[i].indexOf(' ') != -1)
                    sQuery += ' "' + keywords[i] + '" &';
                else
                    sQuery += ' ' + keywords[i] + ' &';
            }
        }
        if (sQuery.substring(sQuery.length - 1) == '&')
            sQuery = sQuery.substring(0, sQuery.length - 1);
        streamQuery = ' (' + sQuery + ') ';
        andMark = '& ';
    }
    if (query['none']) {
        keywords = query['none'].split(',');
        sQuery = "";
        for (i = 0; i < keywords.length; i++) {
            keywords[i] = keywords[i].trim();
            if (keywords[i].length != 0)
                if (keywords[i].indexOf('-') != -1 || keywords[i].indexOf(' ') != -1)
                    sQuery += ' "' + keywords[i] + '" &';
                else
                    sQuery += ' ' + keywords[i] + ' &';
        }
        if (sQuery.substring(sQuery.length - 1) == '&')
            sQuery = andMark + '- (' + sQuery.substring(0, sQuery.length - 1) + ') ';
        streamQuery += sQuery;
        andMark = '& ';
    }
    if (query['any']) {
        keywords = query['any'].split(',');
        sQuery = "";
        for (i = 0; i < keywords.length; i++) {
            keywords[i] = keywords[i].trim();
            if (keywords[i].length != 0)
                if (keywords[i].indexOf('-') != -1 || keywords[i].indexOf(' ') != -1)
                    sQuery += ' "' + keywords[i] + '" |';
                else
                    sQuery += ' ' + keywords[i] + ' |';
        }
        if (sQuery.substring(sQuery.length - 1) == '|')
            sQuery = sQuery.substring(0, sQuery.length - 1);
        streamQuery += andMark + ' \n( ' + sQuery + ' ) ';
        andMark = '& ';
    }
    return streamQuery;
}


$(document).on('click', '.viewport div.folders-content ul.main-section-nav a:not(.edit-button,#all-groups,#all-folders,.btn)', function(e) {
    if ($(this).attr('data-platform') != $('.viewport div.folders-content ul.main-section-nav a.expanded-folder').attr('data-platform')) {
        $('div.mozaic-widget.widget-user_transient_list').empty();
    }
    $(this).parent('li').parent('ul').children('li').children('a').attr('class', 'expand-folder all_users');
    $(this).attr('class', 'expand-folder all_users expanded-folder');
    switch ($(this).attr('data-platform')) {
        case 'all_accounts':
            $('div.folders-content h1.stream-title i.icon-platform-type').parent().children('span').text('All accounts');
            var pl = new SOAPClientParameters();
            SOAPClient.invoke("/m/", "getAccounts", pl, true, getaccounts_callback);
            break;
        case 'twitter':
            $('div.folders-content h1.stream-title i.icon-platform-type').parent().children('span').text('Twitter');
            getSocialAccounts();
            break;
        case 'facebook':
            $('div.folders-content h1.stream-title i.icon-platform-type').parent().children('span').text('Facebook');
            getSocialAccounts();
            break;
        case 'googleplus':
            $('div.folders-content h1.stream-title i.icon-platform-type').parent().children('span').text('Google+');
            getSocialAccounts();
            break;
        case 'linkedin':
            $('div.folders-content h1.stream-title i.icon-platform-type').parent().children('span').text('LinkedIn');
            getSocialAccounts();
            break;
    }
});

function gettwitters_callback(r) {
    if (r["screenname"] != 'undefined' && r["accountid"] != 'undefined') {
        var screenname = r["screenname"].split(';');
        var accountid = r["accountid"].split(';');
        var html = '';
        for (i = 0; i < screenname.length - 1; i++) {
            var li = '<li class="mozaic-widget item- group-tab widget-user_item" data-id="" data-widget="user_item" data-params="" data-guid="widget-2131" data-initialized="true" style="padding-top: 9px;">' +
                    '<a class="expand-folder" data-id="">' +
                    '<div class="user-image-holder holder-Contributor">' +
                    '<img class="group-tab-user-img " src="Images/icon-twitter.png"></div><span class="group-tab-user-name ">' + screenname[i] + '<em></em></span>' +
                    '<span class="group-tab-user-stats">' + accountid[i] + '</span><span class="group-tab-user-stats user-stats-hover"></span></a>' +
                    '<div class="buttons-container">' +
                    '<div id="edit_account" class="btn-holder edit-button"><a class="edit-user btn btn-small edit-button" data-type="twitter"><i class="icon-edit"></i><span>Edit</span></a></div><div id="delete_account" class="btn-holder delete-button"><a class="insert-delete-form delete-user btn btn-small delete-button" data-type="twitter"><i class="icon-delete-folder"></i><span>Delete</span></a></div></div></li>';
            html = html + li;
        }

        $('div.mozaic-widget.widget-user_transient_list').html(html);

    } else {
        $('div.mozaic-widget.widget-user_transient_list').empty();
    }
}

function getfacebooks_callback(r) {
    if (r["screenname"] != 'undefined' && r["accountid"] != 'undefined') {
        var screenname = r["screenname"].split(';');
        var accountid = r["accountid"].split(';');
        var html = '';
        for (i = 0; i < screenname.length - 1; i++) {
            var li = '<li class="mozaic-widget item- group-tab widget-user_item" data-id="" data-widget="user_item" data-params="" data-guid="widget-2131" data-initialized="true" style="padding-top: 9px;">' +
                    '<a class="expand-folder" data-id="">' +
                    '<div class="user-image-holder holder-Contributor">' +
                    '<img class="group-tab-user-img " src="Images/icon-facebook.png"></div><span class="group-tab-user-name ">' + screenname[i] + '<em></em></span>' +
                    '<span class="group-tab-user-stats">' + accountid[i] + '</span><span class="group-tab-user-stats user-stats-hover"></span></a>' +
                    '<div class="buttons-container">' +
                    '<div id="edit_account" class="btn-holder edit-button"><a class="edit-user btn btn-small edit-button" data-type="facebook"><i class="icon-edit"></i><span>Edit</span></a></div><div id="delete_account" class="btn-holder delete-button"><a class="insert-delete-form delete-user btn btn-small delete-button" data-type="facebook"><i class="icon-delete-folder"></i><span>Delete</span></a></div></div></li>';
            html = html + li;
        }
        $('div.mozaic-widget.widget-user_transient_list').html(html);

    } else {
        $('div.mozaic-widget.widget-user_transient_list').empty();
    }
}

function getgoogles_callback(r) {
    if (r["screenname"] != 'undefined' && r["accountid"] != 'undefined') {
        var screenname = r["screenname"].split(';');
        var accountid = r["accountid"].split(';');
        var html = '';
        for (i = 0; i < screenname.length - 1; i++) {
            var li = '<li class="mozaic-widget item- group-tab widget-user_item" data-id="" data-widget="user_item" data-params="" data-guid="widget-2131" data-initialized="true" style="padding-top: 9px;">' +
                    '<a class="expand-folder" data-id="">' +
                    '<div class="user-image-holder holder-Contributor">' +
                    '<img class="group-tab-user-img " src="Images/icon-google.png"></div><span class="group-tab-user-name ">' + screenname[i] + '<em></em></span>' +
                    '<span class="group-tab-user-stats">' + accountid[i] + '</span><span class="group-tab-user-stats user-stats-hover"></span></a>' +
                    '<div class="buttons-container">' +
                    '<div id="edit_account" class="btn-holder edit-button"><a class="edit-user btn btn-small edit-button demo g-interactivepost" data-type="googleplus" id="myBtn"' +
                    'data-clientid="208044150507.apps.googleusercontent.com"' +
                    'data-contenturl="https://developers.google.com/+/web/share/interactive"' +
                    'data-calltoactionlabel="INVITE"' +
                    'data-calltoactionurl="https://developers.google.com/+/web/share/interactive?invite=true"' +
                    'data-cookiepolicy="single_host_origin"' +
                    'data-prefilltext="Come learn about interactive posts with me!">' +
                    '<i class="icon-edit"></i>' +
                    '<span>Edit</span>' +
                    '</a></div><div id="delete_account" class="btn-holder delete-button"><a class="insert-delete-form delete-user btn btn-small delete-button" data-type="googleplus"><i class="icon-delete-folder"></i><span>Delete</span></a></div></div></li>';
            html = html + li;
        }

        $('div.mozaic-widget.widget-user_transient_list').html(html);
        var po = document.createElement('script');
        po.type = 'text/javascript';
        po.async = true;
        po.src = 'https://apis.google.com/js/plusone.js';
        var s = document.getElementsByTagName('script')[0];
        s.parentNode.insertBefore(po, s);

    } else {
        $('div.mozaic-widget.widget-user_transient_list').empty();
    }
}

function getlinkedins_callback(r) {
    if (r["screenname"] != 'undefined' && r["accountid"] != 'undefined') {
        var screenname = r["screenname"].split(';');
        var accountid = r["accountid"].split(';');
        var html = '';
        for (i = 0; i < screenname.length - 1; i++) {
            var li = '<li class="mozaic-widget item- group-tab widget-user_item" data-id="" data-widget="user_item" data-params="" data-guid="widget-2131" data-initialized="true" style="padding-top: 9px;">' +
                    '<a class="expand-folder" data-id="">' +
                    '<div class="user-image-holder holder-Contributor">' +
                    '<img class="group-tab-user-img " src="Images/icon-linkedin.png"></div><span class="group-tab-user-name ">' + screenname[i] + '<em></em></span>' +
                    '<span class="group-tab-user-stats">' + accountid[i] + '</span><span class="group-tab-user-stats user-stats-hover"></span></a>' +
                    '<div class="buttons-container">' +
                    '<div id="edit_account" class="btn-holder edit-button"><a class="edit-user btn btn-small edit-button" data-type="linkedin"><i class="icon-edit"></i><span>Edit</span></a></div><div id="delete_account" class="btn-holder delete-button"><a class="insert-delete-form delete-user btn btn-small delete-button" data-type="linkedin"><i class="icon-delete-folder"></i><span>Delete</span></a></div></div></li>';
            html = html + li;
        }

        $('div.mozaic-widget.widget-user_transient_list').html(html);

    } else {
        $('div.mozaic-widget.widget-user_transient_list').empty();
    }
}

$(document).on('click', 'div#delete_account a', function(e) {
    var pl = new SOAPClientParameters();
    $id = $(this).parent('div').parent('div').parent('li').children('a').children('span.group-tab-user-stats:not(.user-stats-hover)').text();
    switch ($(this).attr('data-type')) {
        case 'twitter':
            pl.add("twitterid", $id);
            SOAPClient.invoke("/m/", "deleteTwitter", pl, true, deletetSocialComplete);
            break;
        case 'facebook':
            pl.add("facebookid", $id);
            SOAPClient.invoke("/m/", "deleteFacebook", pl, true, deletetSocialComplete);
            break;
        case 'googleplus':
            pl.add("googleid", $id);
            SOAPClient.invoke("/m/", "deleteGoogle", pl, true, deletetSocialComplete);
            break;
        case 'linkedin':
            pl.add("linkedinid", $id);
            SOAPClient.invoke("/m/", "deleteLinkedIn", pl, true, deletetSocialComplete);
            break;

    }
});

function deletetSocialComplete(r) {
    if (r == "true") {
        getSocialAccounts();
    }
}

function getSocialAccounts() {
    switch ($('.viewport div.folders-content ul.main-section-nav a.expanded-folder').attr('data-platform')) {
        case 'twitter':
            $('div.mozaic-widget.widget-user_transient_list').html('');
            var pl = new SOAPClientParameters();
            SOAPClient.invoke("/m/", "getTwitters", pl, true, gettwitters_callback);
            break;
        case 'facebook':
            $('div.mozaic-widget.widget-user_transient_list').html('');
            var pl = new SOAPClientParameters();
            SOAPClient.invoke("/m/", "getFacebooks", pl, true, getfacebooks_callback);
            break;
        case 'googleplus':
            $('div.mozaic-widget.widget-user_transient_list').html('');
            var pl = new SOAPClientParameters();
            SOAPClient.invoke("/m/", "getGoogles", pl, true, getgoogles_callback);
            break;
        case 'linkedin':
            $('div.mozaic-widget.widget-user_transient_list').html('');
            var pl = new SOAPClientParameters();
            SOAPClient.invoke("/m/", "getLinkedIns", pl, true, getlinkedins_callback);
            break;
        case 'all_accounts':
            $('div.mozaic-widget.widget-user_transient_list').html('');
            var pl = new SOAPClientParameters();
            SOAPClient.invoke("/m/", "getAccounts", pl, true, getaccounts_callback);
            break;
    }
}

$(document).on('click', 'div#edit_account a', function(e) {
    var pl = new SOAPClientParameters();
    switch ($('div#edit_account a').attr('data-type')) {
        case 'retweet':
            pl.add("message", "Post a Tweet: www.google.com");
            SOAPClient.invoke("/m/", "postTweet", pl, true, test_callback);
            break;
        case 'facebook':
            pl.add("message", "Post a Test Tweet");
            pl.add("link", "www.smartsolutiontoday.com");
            SOAPClient.invoke("/m/", "postFacebookStatus", pl, true, test_callback);
            break;
        case 'googleplus':
            break;
        case 'linkedin':
            pl.add("message", "Post a Test Status");
            SOAPClient.invoke("/m/", "postLinkedInStatus", pl, true, test_callback);
            break;
    }
});

function test_callback(r) {
    retweetObj.addClass('social-shared');
    var tmr = setTimeout(function(data) {
        retweetObj.removeClass('social-shared');
        clearInterval(tmr);
    }, 1000);
    retweetObj.parents('li').find('.open').removeClass('open');
    $('#modal').removeClass('in');
    startInterval(1);
}

$(document).on('click', 'ul.dropdown-menu.pull-right a', function(e) {
    var pl = new SOAPClientParameters();
    switch ($(this).attr('data-type')) {
        case 'twitter':
            SOAPClient.invoke("/m/", "getTwitters", pl, true, hastwitter_callback);
            break;
        case 'facebook':
            SOAPClient.invoke("/m/", "getFacebooks", pl, true, hasfacebook_callback);
            break;
        case 'googleplus':
            SOAPClient.invoke("/m/", "getGoogles", pl, true, hasgoogle_callback);
            break;
        case 'linkedin':
            SOAPClient.invoke("/m/", "getLinkedIns", pl, true, haslinkedin_callback);
            break;
    }
});

function hastwitter_callback(r) {
    if (r["screenname"] == 'undefined') {
        var win = window.open('authorizeTwitter');
        var ttimer = setInterval(function() {
            if (win.closed) {
                clearInterval(ttimer);
                getSocialAccounts();
            }
        }, 1000);
    }
}

function hasfacebook_callback(r) {
    if (r["screenname"] == 'undefined') {
        var win = window.open('authorizeFacebook');
        var ttimer = setInterval(function() {
            if (win.closed) {
                clearInterval(ttimer);
                getSocialAccounts();
            }
        }, 1000);
    }
}

function hasgoogle_callback(r) {
    if (r["screenname"] == 'undefined') {
        var win = window.open('authorizeGoogle');
        var ttimer = setInterval(function() {
            if (win.closed) {
                clearInterval(ttimer);
                getSocialAccounts();
            }
        }, 1000);
    }
}

function haslinkedin_callback(r) {
    if (r["screenname"] == 'undefined') {
        var win = window.open('authorizeLinkedIn');
        var ttimer = setInterval(function() {
            if (win.closed) {
                clearInterval(ttimer);
                getSocialAccounts();
            }
        }, 1000);
    }
}

$(document).on('click', '.retweet_dropdown a', function(data) {
    retweetObj = $(this).parents('.retweet_dropdown').find('button');
    var pl = new SOAPClientParameters();
    shareMessageId = $(this).parents('li.retweet_dropdown').attr('messageId');
    shareStreamId = $(this).parents('li.retweet_dropdown').attr('streamId');
    message = $(this).parents('.mention-content').find('.mention-text').get(0).innerText.trim();
    link = $(this).parents('.mention-content').find('.mention-title a').attr('href');
    if ($('.modal-body').html() !== shareMessage) {
        var title = '';
        $('.modal-body').html(shareMessage);
        messageLink = link;
        messageContent = message;
        messageType = $(this).attr('data-action');
        $('.modal-body').find('textarea').html(message);
        switch ($(this).attr('data-action')) {
            case 'retweet':
                title = 'Tweet';
                break;
            case 'facebook':
                title = 'Share on your facebook';
                break;
            case 'linkedin':
                title = 'Share on your linkedin';
                break;
            default:
                return;
        }
        $('.modal-title').html(title);
    }

    $('.modal-backdrop').css('display', 'block');
    $('#modal').css('width', '380px');
    $('#modal').css('margin-left', '-190px');
    $('.modal-backdrop').addClass('in');
    $('.modal-backdrop').css('z-index', '9999');
    $('#modal').css('z-index', '10000');
    $('#modal').addClass("in");

});

$(document).on('click', '.widget-folder_with_streams .expand-folder:not(.folder-fade)', function(data) {
    if ($(this).hasClass('expanded-folder')) {
        $(this).removeClass('expanded-folder');
    }
    else if ($(this).hasClass('expand-folder')) {
        $(this).addClass('expanded-folder');
    }
});

$(document).on('click', '#delete-folder', function() {
    var folderid = $('.folders-content .expanded-folder').parent().attr('data-id');
    if (folderid == 0) {
        alert("You cannot delete root folder!");
    }
    else {
        if (confirm("Do you really want to delete folder '" +
                $('.stream-title').last().children('span').html() +
                "'?\nAll the sub-folders streams are also deleted.\nPlease be careful!")) {
            var pl = new SOAPClientParameters();
            pl.add("folderId", $('.expanded-folder').parent().attr('data-id'));
            SOAPClient.invoke("/m/", "deleteFolder", pl, true, deleteFolder_complete);
        }
    }
});

function deleteFolder_complete() {
    $('#all-folder').click();
    var pl = new SOAPClientParameters();
    SOAPClient.invoke("m/", "getFolder", pl, true, getfolder_callback);
    if ($('.expanded-folder').attr('id') != 'all-folders') {
        $('.expanded-folder').parent().remove();
        $('#all-folders').click();
        $.post('folder', function(data) {
            $('.widget-directory_list').first().html(data);
            navigateFolder();
        });
        $.post("/ajax/addStreamS3", function(data) {
            addStreamS3 = data;
        });
    }
    else {
        $('#all-folders').parent().attr('data-id', 0);
        currentFolder = 0;
    }
}

$(document).on('click', '#folderlist .edit-button a', function(event) {
    var taga = $(this).parents('.widget-folder_item').find('a').first();
    $(this).parents('li').addClass('editing');
});

function getaccounts_callback(r) {
    if (r["screenname"] != 'undefined' && r["accountid"] != 'undefined') {
        var html = '';
        var screenname_twitter = r["screenname"].split('twitter')[0];
        var id_twitter = r["accountid"].split('twitter')[0];
        var screenname_facebook = r["screenname"].split('twitter')[1].split('facebook')[0];
        var id_facebook = r["accountid"].split('twitter')[1].split('facebook')[0];
        var screenname_google = r["screenname"].split('facebook')[1].split('google')[0];
        var id_google = r["accountid"].split('facebook')[1].split('google')[0];
        var screenname_linkedin = r["screenname"].split('google')[1].split('linkedin')[0];
        var id_linkedin = r["accountid"].split('google')[1].split('linkedin')[0];
        var twitterscreenname = screenname_twitter.split(';');
        var twitterid = id_twitter.split(';');
        for (i = 0; i < twitterscreenname.length - 1; i++) {
            var li = '<li class="mozaic-widget item- group-tab widget-user_item" data-id="" data-widget="user_item" data-params="" data-guid="widget-2131" data-initialized="true" style="padding-top: 9px;">' +
                    '<a class="expand-folder" data-id="">' +
                    '<div class="user-image-holder holder-Contributor">' +
                    '<img class="group-tab-user-img " src="Images/icon-twitter.png"></div><span class="group-tab-user-name ">' + twitterscreenname[i] + '<em></em></span>' +
                    '<span class="group-tab-user-stats">' + twitterid[i] + '</span><span class="group-tab-user-stats user-stats-hover"></span></a>' +
                    '<div class="buttons-container">' +
                    '<div id="edit_account" class="btn-holder edit-button"><a class="edit-user btn btn-small edit-button" data-type="twitter"><i class="icon-edit"></i><span>Edit</span></a></div><div id="delete_account" class="btn-holder delete-button"><a class="insert-delete-form delete-user btn btn-small delete-button" data-type="twitter"><i class="icon-delete-folder"></i><span>Delete</span></a></div></div></li>';
            html = html + li;
        }
        var facebookscreenname = screenname_facebook.split(';');
        var facebookid = id_facebook.split(';');
        for (i = 0; i < facebookscreenname.length - 1; i++) {
            var li = '<li class="mozaic-widget item- group-tab widget-user_item" data-id="" data-widget="user_item" data-params="" data-guid="widget-2131" data-initialized="true" style="padding-top: 9px;">' +
                    '<a class="expand-folder" data-id="">' +
                    '<div class="user-image-holder holder-Contributor">' +
                    '<img class="group-tab-user-img " src="Images/icon-facebook.png"></div><span class="group-tab-user-name ">' + facebookscreenname[i] + '<em></em></span>' +
                    '<span class="group-tab-user-stats">' + facebookid[i] + '</span><span class="group-tab-user-stats user-stats-hover"></span></a>' +
                    '<div class="buttons-container">' +
                    '<div id="edit_account" class="btn-holder edit-button"><a class="edit-user btn btn-small edit-button" data-type="facebook"><i class="icon-edit"></i><span>Edit</span></a></div><div id="delete_account" class="btn-holder delete-button"><a class="insert-delete-form delete-user btn btn-small delete-button" data-type="facebook"><i class="icon-delete-folder"></i><span>Delete</span></a></div></div></li>';
            html = html + li;
        }
        var googlescreenname = screenname_google.split(';');
        var googleid = id_google.split(';');
        for (i = 0; i < googlescreenname.length - 1; i++) {
            var li = '<li class="mozaic-widget item- group-tab widget-user_item" data-id="" data-widget="user_item" data-params="" data-guid="widget-2131" data-initialized="true" style="padding-top: 9px;">' +
                    '<a class="expand-folder" data-id="">' +
                    '<div class="user-image-holder holder-Contributor">' +
                    '<img class="group-tab-user-img " src="Images/icon-google.png"></div><span class="group-tab-user-name ">' + googlescreenname[i] + '<em></em></span>' +
                    '<span class="group-tab-user-stats">' + googleid[i] + '</span><span class="group-tab-user-stats user-stats-hover"></span></a>' +
                    '<div class="buttons-container">' +
                    '<div id="edit_account" class="btn-holder edit-button"><a class="edit-user btn btn-small edit-button" data-type="googleplus"><i class="icon-edit"></i><span>Edit</span></a></div><div id="delete_account" class="btn-holder delete-button"><a class="insert-delete-form delete-user btn btn-small delete-button" data-type="googleplus"><i class="icon-delete-folder"></i><span>Delete</span></a></div></div></li>';
            html = html + li;
        }
        var linkedinscreenname = screenname_linkedin.split(';');
        var linkedinid = id_linkedin.split(';');
        for (i = 0; i < linkedinscreenname.length - 1; i++) {
            var li = '<li class="mozaic-widget item- group-tab widget-user_item" data-id="" data-widget="user_item" data-params="" data-guid="widget-2131" data-initialized="true" style="padding-top: 9px;">' +
                    '<a class="expand-folder" data-id="">' +
                    '<div class="user-image-holder holder-Contributor">' +
                    '<img class="group-tab-user-img " src="Images/icon-linkedin.png"></div><span class="group-tab-user-name ">' + linkedinscreenname[i] + '<em></em></span>' +
                    '<span class="group-tab-user-stats">' + linkedinid[i] + '</span><span class="group-tab-user-stats user-stats-hover"></span></a>' +
                    '<div class="buttons-container">' +
                    '<div id="edit_account" class="btn-holder edit-button"><a class="edit-user btn btn-small edit-button" data-type="linkedin"><i class="icon-edit"></i><span>Edit</span></a></div><div id="delete_account" class="btn-holder delete-button"><a class="insert-delete-form delete-user btn btn-small delete-button" data-type="linkedin"><i class="icon-delete-folder"></i><span>Delete</span></a></div></div></li>';
            html = html + li;
        }
        $('div.mozaic-widget.widget-user_transient_list').html(html);
    } else {
        $('div.mozaic-widget.widget-user_transient_list').empty();
    }
}

$(document).on('click', 'blockquote a:first-child', function(event) {
    if ($(this).html() == 'show quote') {
        $(this).parent().height($(this).parent()[0].scrollHeight);
        $(this).html('hide quote');
    }
    else {
        $(this).parent().height(18);
        $(this).html('show quote');
    }
});

$(document).on('click', 'span.three-dots', function(event) {
    if ($('.query-container')[0].offsetHeight == 44)
        $('.query-container').height($('.query-container')[0].scrollHeight);
    else
        $('.query-container').height(44);
});

$(document).on('click', '.toggle-link', function(event) {
    if ($(this).html() == 'show links') {
        $(this).parents('li').find('.mention-content').find('.parsed-link').removeClass('hide');
        $(this).html('hide links');
    }
    else {
        $(this).parents('li').find('.mention-content').find('.parsed-link').addClass('hide');
        $(this).html('show links');
    }
});

$(document).on('hover', '.main-nav', function(event) {
    var bottombar = document.getElementsByClassName('bottom-main-nav')[0].parentElement;
    var offsetTop = bottombar.offsetTop;
    var ulstream = document.getElementsByClassName('stream-menu')[0];
    ulstream.style.height = offsetTop - ulstream.offsetTop + 'px';
});

var qtimeOut;
$(document).on('mouseenter', '.query-container', function(event) {
    if ($(this).height() == 44) {
        qtimeOut = setTimeout(function() {
            $('.three-dots').click();
        }, 1000);
    }
});

$(document).on('mouseleave', '.query-container', function(event) {
    if ($(this).height() > 44) {
        qtimeOut = setTimeout(function() {
            $('.three-dots').click();
        }, 1000);
    }
});

$(document).on('click', 'body.preview ul.widget-signals li', function(event) {
    href = $(this).find('.action-color-hover').attr('href');
    if ($('.signal-preview iframe').attr('src') != href)
        preview(href);
    return false;
});

$(document).on('click', '.filter-back-button', function(event) {
    $(this).parents('.opened').removeClass('opened');
});

$(document).on('click', '.clear-filters .btn', function(event) {
    clearFilter();
});

var selecting = false;
var currentFilter;
$(document).on('click', '.filter-container-list li', function(e) {
    var different = false;
    var a = $(this).parents('.mozaic-widget').first().find('.filter-button a');
    a.children('span').html(name);
    var id = $(this).attr('data-value');
    var name = this.innerText.trim();
    if (a.attr('data-value') != id)
        different = true;
    if (!e.ctrlKey) {
        a.attr('data-value', id);
        a.children('span').text(name);
        $(this).addClass('selected');
        $(this).parent('ul').children('.selected').removeClass('selected');
        $(this).parents('.opened').removeClass('opened');
        if (different) {
            applyFilter($(this));
        }
    } else {
        if ($(this).attr('data-value') !== '0') { //all item
            $(this).parent('ul').children().first().removeClass('selected');
            selecting = true;
            if ($(this).hasClass('selected')) {
                $(this).removeClass('selected');
                if ($(this).parent('ul').children('.selected').length === 0)
                    $(this).parent('ul').children().first().addClass('selected');
            } else {
                $(this).addClass('selected');
            }
            var ids = [];
            var names = [];
            $(this).parent('ul').children('.selected').each(function() {
                ids.push($(this).attr('data-value'));
                names.push($(this).text().trim());
            });
            a.attr('data-value', ids.join(','));
            a.children('span').text(names.join(', '));
            a.children('span').attr('title', names.join(', '));
            currentFilter = $(this);
        } else {
            $(this).parent('ul').children('.selected').removeClass('selected');
            $(this).parents('.opened').removeClass('opened');
            if (a.attr('data-value') !== '0') {
                a.attr('data-value', '0');
                a.children('span').text(name);
                selecting = false;
                applyFilter($(this));
            }
        }
    }
});

window.onkeyup = function(e) {
    if (e.keyCode == 17 && selecting) {
        selecting = false;
        applyFilter(currentFilter);
        currentFilter = undefined;
    }
}

$(document).on('click', '#sentiment-filter-widget a', function(event) {
    if (!metricsProcessing)
        applyFilter($(this));
});

$(document).on('click', '#thismonth-filter-widget a', function(event) {
    $('#from').datepicker('setDate', orgDateFrom);
    $('#to').datepicker('setDate', orgDateTo);
    var streamId = window.location.href.split('#')[1].split('/')[1];
    setCookie('stream[' + streamId + '][datefrom]', $("#from").datepicker().val(), 1);
    setCookie('stream[' + streamId + '][dateto]', $("#to").datepicker().val(), 1);
    applyFilter();
    if (!metricsProcessing)
        applyFilter($(this));
});
$(document).on('click', '#date-filter-widget', function(event) {
    $('#thismonth-filter-widget .selected').removeClass('selected');
});

$(document).on('click', '.toggle', function(event) {
    if (window.location.href.split('#')[1])
        param = window.location.href.split('#')[1].split('/')[0];
    else
        param = '';
    if ($(this).hasClass('checked')) {
        $(this).removeClass('checked').children('q').html('OFF');
        if (param.toLowerCase() == 'stream') {
            if ($(document.body).hasClass('preview'))
                $(document.body).removeClass('preview');
            hidePreview();
        }
    }
    else {
        $(this).addClass('checked').children('q').html('ON');
        if (param.toLowerCase() == 'stream') {
            if (!$(document.body).hasClass('preview'))
                $(document.body).addClass('preview');
            preview();
        }
    }
});

$(document).on('mouseenter', 'body.preview .preview-topbar', function(e) {
    $('.left-nav').attr('class', 'left-nav visible');
    $('.list-viewport').css('opacity', '0.1');
});

$(document).on('mouseleave', 'body.preview .action-nav', function(e) {
    $('.left-nav').attr('class', 'left-nav hidden');
    $('.list-viewport').css('opacity', '1');
});

$(document).on('click', '.video-thumb-container', function(e) {
    var videoId = $(this).children('div').attr('data-video-id');
    var html = '<div style="" id="videocontainer-' + videoId + '"><iframe width="480" height="360" src="http://www.youtube.com/embed/' + videoId + '?wmode=opaque&amp;autoplay=1" frameborder="0" allowfullscreen=""></iframe></div>';
    $(this).addClass('hide');
    this.outerHTML += html;
    $('.main-content').height($(window).height() - 22);
});

$(document).on('click', 'ul.message-action-filter li', function(e) {
    $('ul.message-action-filter .active-section').removeClass('active-section');
    $(this).addClass('active-section');

    //Change icon then apply filter
    var className = $(this).find('i').attr('class');
    $('.active-popup').attr('class', className + ' active-popup');
    $(this).parent('ul').attr('class', 'message-action-filter hidden');

    applyFilter();
});

var btnAction;

$(document).on('click', '.mention-actions.mention-favorite', function(e) {
    btnAction = $(this);
    var shareLi = $(this).parents('ul.mention-action-bar').children('li').first();
    var messageId = shareLi.attr('messageid');
    var threadId = shareLi.attr('threadid');
    var streamId = shareLi.attr('streamid');
    var type = 1;

    var pl = new SOAPClientParameters();
    pl.add('messageActionType', type);
    pl.add('messageId', messageId);
    pl.add('threadId', threadId);
    pl.add('streamId', streamId);
    SOAPClient.invoke('/m', 'addMessageAction', pl, true, actionComplete);
});

function actionComplete(r) {
    if (r == 'succeed') {
        var i = btnAction.find('i');
        if ($('ul.message-action-filter li.active-section').length > 0) {
            switch ($('ul.message-action-filter li.active-section i').attr('class')) {
                case 'icon-main-menu-favorite':
                    if (i.hasClass('icon-action-favorite') || i.hasClass('icon-action-archive') || i.hasClass('icon-action-trash'))
                        slideRemove(btnAction.parents('li.widget-story_signal'));
                    break;
                case 'icon-main-menu-archive':
                    if (i.hasClass('icon-action-archive') || i.hasClass('icon-action-trash'))
                        slideRemove(btnAction.parents('li.widget-story_signal'));
                    break;
                case 'icon-main-menu-trash':
                    if (i.hasClass('icon-action-trash'))
                        slideRemove(btnAction.parents('li.widget-story_signal'));
                    break;
            }
        }
        else
        if (i.hasClass('icon-action-archive') || i.hasClass('icon-action-trash'))
            slideRemove(btnAction.parents('li.widget-story_signal'));

        if (i.hasClass('icon-active')) {
            i.removeClass('icon-active');
            tooltipText = '';
            switch (i.attr('class').split(' ')[0]) {
                case 'icon-action-favorite':
                    tooltipText = 'Add to Favorite';
                    i.parent().next().children('.tooltip-inner').html(tooltipText);
                    i.parent().next().css('margin-left', '-34px');
                    break;
                case 'icon-action-archive':
                    tooltipText = 'Archive this message';
                    i.parent().next().children('.tooltip-inner').html(tooltipText);
                    i.parent().next().css('margin-left', '-59px');
                    break;
                case 'icon-action-trash':
                    tooltipText = 'Move to trash';
                    i.parent().next().children('.tooltip-inner').html(tooltipText);
                    i.parent().next().css('margin-left', '-42px');
                    break;
            }
        }
        else {
            btnAction.find('i').addClass('icon-active');
            tooltipText = '';
            switch (i.attr('class').split(' ')[0]) {
                case 'icon-action-favorite':
                    tooltipText = 'Remove from Favorite';
                    i.parent().next().children('.tooltip-inner').html(tooltipText);
                    i.parent().next().css('margin-left', '-50px');
                    break;
                case 'icon-action-archive':
                    tooltipText = 'Unrchive this message';
                    i.parent().next().children('.tooltip-inner').html(tooltipText);
                    i.parent().next().css('margin-left', '-65px');
                    break;
                case 'icon-action-trash':
                    tooltipText = 'Undo Trash';
                    i.parent().next().children('.tooltip-inner').html(tooltipText);
                    i.parent().next().css('margin-left', '-35px');
                    break;
            }
        }
    }
}

function slideRemove(element) {
    var width = element.width();
    var height = element.height();
    element.css('width', width);
    element.css('height', height);
    setTimeout(function() {
        element.css('-webkit-transition', 'all 0.1s ease-in-out');
        element.css('-moz-transition', 'all 0.1s ease-in-out');
        element.css('-o-transition', 'all 0.1s ease-in-out');
        element.css('transition', 'all 0.1s ease-in-out');
        element.css('margin-left', -width + 'px');
        setTimeout(function(e) {
            element.css('height', '0px');
            setTimeout(function(e) {
                element.remove();
                if ($('ul.widget-signals').height() < 1000) {
                    loadMoreMessage();
                }
            }, 200)
        }, 800);
    }, 200);
}

function loadMoreMessage() {
    if ($('.signal-preview').length == 1 && $('ul.widget-signals').length == 1)
        $('.loading').width($('.signal-preview').offset().left - $('ul.widget-signals').offset().left);
    $('.loading').height(30);
    page++;
    streamId = window.location.href.split('#')[1].split('/')[1];
    filter = $(this).parents('.opened').attr('id');
    dateFrom = $('#from').datepicker().val();
    dateTo = $('#to').datepicker().val();
    index = streamEntryEachPage * (page - 1);
    sentiment = $('#sentiment-filter-widget a.selected').attr('data-value');
    if ($('#sentiment-filter-widget a.selected').length == 0)
        sentiment = 0;
    language = $('#language-filter-widget').find('a').attr('data-value');
    tag = $('#tag-filter-widget').find('a').attr('data-value');
    type = $('#platform-filter-widget').find('a').attr('data-value');
    pause = true;
    var messageActionFilter;
    if ($('ul.message-action-filter .active-section').length != 0)
        messageActionFilter = '?filter=' + $('ul.message-action-filter .active-section i').attr('class').split(' ')[0].split('icon-main-menu-')[1];
    loadpStream(streamId, dateFrom, dateTo, index, streamEntryEachPage, language, tag, sentiment, messageActionFilter, type);
}

$(document).on('click', '.mention-actions.mention-archive', function(e) {
    btnAction = $(this);
    var shareLi = $(this).parents('ul.mention-action-bar').children('li').first();
    var messageId = shareLi.attr('messageid');
    var threadId = shareLi.attr('threadid');
    var streamId = shareLi.attr('streamid');
    var type = 2;

    var pl = new SOAPClientParameters();
    pl.add('messageActionType', type);
    pl.add('messageId', messageId);
    pl.add('threadId', threadId);
    pl.add('streamId', streamId);
    SOAPClient.invoke('/m', 'addMessageAction', pl, true, actionComplete);
});

$(document).on('click', '.mention-actions.mention-trash', function(e) {
    btnAction = $(this);
    var shareLi = $(this).parents('ul.mention-action-bar').children('li').first();
    var messageId = shareLi.attr('messageid');
    var threadId = shareLi.attr('threadid');
    var streamId = shareLi.attr('streamid');
    var type = 4;

    var pl = new SOAPClientParameters();
    pl.add('messageActionType', type);
    pl.add('messageId', messageId);
    pl.add('threadId', threadId);
    pl.add('streamId', streamId);
    SOAPClient.invoke('/m', 'addMessageAction', pl, true, actionComplete);
});

$(document).on('click', '.spam-link-author', function(e) {
    btnAction = $(this);
    var shareLi = $(this).parents('ul.mention-action-bar').children('li').first();
    var messageId = shareLi.attr('messageid');
    var threadId = shareLi.attr('threadid');
    var streamId = shareLi.attr('streamid');
    var author = $(this).first().parents('.widget-story_signal').find('.mention-short-url a').first().next().html();
    var source = $(this).parents('.widget-story_signal').find('.mention-short-url a').first().attr('source');

    var pl = new SOAPClientParameters();
    pl.add('messageId', messageId);
    pl.add('threadId', threadId);
    pl.add('streamId', streamId);
    pl.add('source', '');
    pl.add('author', author);
    SOAPClient.invoke('/m', 'markAsSpam', pl, true, markSpamComplete);
});

$(document).on('click', '.spam-link-source', function(e) {
    btnAction = $(this);
    var shareLi = $(this).parents('ul.mention-action-bar').children('li').first();
    var messageId = shareLi.attr('messageid');
    var threadId = shareLi.attr('threadid');
    var streamId = shareLi.attr('streamid');
    var author = $(this).parents('.widget-story_signal').find('.mention-short-url a').first().next().html();
    var source = $(this).parents('.widget-story_signal').find('.mention-short-url a').first().attr('source');

    var pl = new SOAPClientParameters();
    pl.add('messageId', messageId);
    pl.add('threadId', threadId);
    pl.add('streamId', streamId);
    pl.add('source', source);
    pl.add('author', '');
    SOAPClient.invoke('/m', 'markAsSpam', pl, true, markSpamComplete);
});

function markSpamComplete(r) {
    if (r == 'succeed') {
        if ($('ul.message-action-filter li.active-section').length > 0) {
            $('ul.message-action-filter li.active-section').click();
        }
        else
            $('#mentions-link-widget a.url-widget-link').click();
    }
}

$(document).on('click', '.remove-spam', function(e) {
    btnAction = $(this);
    var shareLi = $(this).parents('ul.mention-action-bar').children('li').first();
    var messageId = shareLi.attr('messageid');
    var threadId = shareLi.attr('threadid');
    var streamId = shareLi.attr('streamid');
    var author = $(this).parents('.widget-story_signal').find('.mention-short-url a').first().next().html();
    var source = $(this).parents('.widget-story_signal').find('.mention-short-url a').first().attr('source');
    var pl = new SOAPClientParameters();
    pl.add('messageId', messageId);
    pl.add('threadId', threadId);
    pl.add('streamId', streamId);
    pl.add('source', source);
    pl.add('author', author);
    SOAPClient.invoke('/m', 'markAsSpam', pl, true, markSpamComplete);
});

$(document).on('mouseover', '.main-section-nav li:first-child a', function(event) {
    if ($(this).attr('tooltipdata') != '' && $(this).attr('tooltipdata') != undefined) {
        $('#main-tooltip .tooltip-inner').html($(this).attr('tooltipdata'));
        var top = $(this).offset().top + $(this).height() / 2 - ($('#main-tooltip').height() + 10) / 2;
        $('#main-tooltip').css('top', top + 'px');
        $('#main-tooltip').css('display', 'block');
    }
});

$(document).on('mouseleave', '.main-section-nav li:first-child a', function(event) {
    $('#main-tooltip').css('display', 'none');
});

$(document).on('click', '#select-more', function(e) {
    messageId = $(this).parents('div.mention-core').find('li.mention-action-button.retweet_dropdown').attr('messageid');
    var streamId = $(this).parents('div.mention-core').find('li.mention-action-button.retweet_dropdown').attr('streamId');
    switch ($(this).val()) {
        case "1":
            var img = $(this).parents('div.mention-core').find('div.profile-img').children('img').attr('src')
            var time = $(this).parents('div.mention-core').find('p.mention-type.additional-timestamp.signals-additional-time').text();
            var threadTitle = $(this).parents('div.mention-core').find('a.action-color-hover').text();
            var icon = $(this).parents('div.mention-core').find('p.mention-short-url').children('img').attr('src');
            var source = $(this).parents('div.mention-core').find('a.action-color-active')[0].text;
            var streamTitle = $(this).parents('div.mention-core').find('a.action-color-active')[1].text;
            var text = $(this).parents('div.mention-core').find('div.mention-text.url-parsed').text();
            replyMail = '<div style="border: solid 1px #cecece;border-top: none;margin-left: 20px;margin-right: 20px;">';
            var data = $(this).parents('div.mention-right-wrapper').find('div.user-author-mention-actions.mention-top-bar');
            for (var i = 0; i < 5 && i <= data.length; i++) {
                replyMail = replyMail + '<div style="min-height:auto;min-height:62px;padding-left: 20px;padding-right: 10px;">' +
                        '<div style="float: left;">' +
                        '<img style="width:32px;min-height:32px;border-radius:0;margin-top: 8px;margin-right: 8px;" src="' + data.eq(i).find('img').attr('src') + '"></div>' +
                        '<div style="float: left; max-width: 70%;">' +
                        '<p style="overflow:hidden;display:block;font-size: 14px !important;margin-top: 0px;margin-bottom: 0px;padding-top: 5px;padding-bottom: 5px;margin-right: 8px;">' +
                        '<strong style="color: #3B5998 !important;font-weight: bold;">' + data.eq(i).find('div.float-left.main-reply-content.url-parsed').children('p').children('strong').text() + '</strong>' +
                        '<span style="color: #333;  margin: 0 2px 0 0;  };">' + data.eq(i).find('div.float-left.main-reply-content.url-parsed').children('p').children('span').text() + '</span></p></div><div>' +
                        '<span style="line-height:22px;float: right;  font-size: 13px;">' + data.eq(i).find('div.float-right').children('span').text() + '</span></div>' +
                        '<div style="clear: right;  margin-top: -0.5em;float: right;"><div>' +
                        '<i style="background-image: url(' + '/Images/fb_icons.png);  background-repeat: no-repeat;  background-size: auto;  background-position: 0 0;  height: 14px;  width: 16px;  };"></i>' +
                        '<div>' + data.eq(i).find('div.thread-details').children('div').text() + '</div></div></div></div>';
            }
            replyMail = replyMail + '</div>';
            dataMail = img + ';' + time + ';' + threadTitle + ';' + icon + ';' + source + ';' + streamTitle + ';' + text;
            if ($('.modal-body').html() !== shareViaEmail) {
                var title = 'Share via your email';
                $('.modal-body').html(shareViaEmail);
                $('.modal-title').html(title);
                messageType = "share via email";
            }
            $('.modal-backdrop').css('display', 'block');
            $('#modal').css('width', '380px');
            $('#modal').css('margin-left', '-190px');
            $('.modal-backdrop').addClass('in');
            $('.modal-backdrop').css('z-index', '9999');
            $('#modal').css('z-index', '10000');
            $('#modal').addClass("in");
            html = $(this).parents('li').html();
            $(this).children('[name="default"]').attr('selected', 'selected');
            break;
    }
});

$(document).on('submit', '.widget-email_form .bbf-form', function(e) {
    $('#error-email').attr('class', 'hide');
    var pl = new SOAPClientParameters();
    var data = '';
    $(this).find('.data-presenting span:not(:last-child)').each(function() {
        var name = $(this).text();
        var email = $(this).attr('email');
        data += name + '|' + email + ';';
    });
    var sendTo = data;
    messageContent = $(this).find('.nicEdit-main').html();
    if (sendTo !== '') {
        var commit = $(this).parents('.widget-email_form').find('.commit');
        commit.attr('disabled', 'disabled');
        commit.next().removeClass('hide');
        pl.add("sendTo", sendTo);
        pl.add("subject", emailSubject.value);
        pl.add("content", messageContent);
        SOAPClient.invoke("/m/", "shareEmail", pl, true, shareEmail_callback);
    }
    return false;
});

function shareEmail_callback(r) {
    if (r === "done") {
        var timeout = setTimeout(function() {
            $('#modal').removeClass('in');
            startInterval(1);
        }, 500);
    } else {
        $('#error-email').html(r);
        $('#error-email').removeClass('hide');
    }
}
var curStreamId, curMessageId, curThreadId, curText, curSource, curDate, curTime, curLink;
$(document).on('submit', '.widget-sms_form .bbf-form', function(e) {
    var data = new Array();
    $(this).find('.data-presenting span:not(:last-child)').each(function() {
        var name = $(this).text();
        var email = $(this).attr('email');
        var pl = new SOAPClientParameters();
        pl.add("phoneNumber", email);
        pl.add("message", c2844_sms.value);
        SOAPClient.invoke("/m/", "sendSMS", pl, true, function(r) {
            var timeout = setTimeout(function() {
                $('#modal').removeClass('in');
                startInterval(1);
                showMessage('Message has been send to: ' + email);
            }, 500);
        });
        data.push(email);
    });
    var sendTo = data;
    messageContent = c2844_sms.value;
    if (sendTo !== '') {
        var commit = $(this).parents('.widget-sms_form').find('.commit');
        commit.attr('disabled', 'disabled');
        commit.next().removeClass('hide');
        var pl = new SOAPClientParameters();
        pl.add("messageId", curMessageId);
        pl.add("streamid", curStreamId);
        pl.add("post", '<a href="' + curLink + '" target="_blank">' + c2844_sms.value + '</a>');
        pl.add("action", '[' + sendTo + '] ' + messageContent);
        SOAPClient.invoke("/m/", "sendSMSToQueue", pl, true, function(r) {
            var timeout = setTimeout(function() {
                $('#modal').removeClass('in');
                startInterval(1);
                //showMessage('Message has been added into queue');
            }, 500);
        });
    }
    return false;
});

$(document).on('click', 'div.thread-details div.numberOfReplies', function(e) {
    var curTop = $('.list-viewport').scrollTop();
    var topReply = $(this).parents('.mention-right-wrapper').find('.thread-replies').first().offset().top;
    $('.list-viewport').animate({scrollTop: topReply + curTop});
});

$(document).on('click', '.reply', function(e) {

    var title = $(this).parents('.mention-right-wrapper').find('.mention-title a').html();
    $('.modal-title').html("Reply on '" + title + "'");
    $('.modal-body').html(replyBox);
    replyPostID = $(this).attr('fbpostid');

    $('.modal-backdrop').css('display', 'block');
    $('#modal').css('width', '380px');
    $('#modal').css('margin-left', '-190px');
    $('.modal-backdrop').addClass('in');
    $('.modal-backdrop').css('z-index', '9999');
    $('#modal').css('z-index', '10000');
    $('#modal').addClass("in");
});

$(document).on('submit', '.widget-reply_form .bbf-form', function(e) {
    $(this).find('.commit').attr('disabled', 'disabled');
    $(this).find('.background-loading-small').removeClass('hide');
    replyMessage = c2844_message.value;
    pl = new SOAPClientParameters();
    pl.add("postid", replyPostID);
    pl.add("message", replyMessage);
    SOAPClient.invoke("/m/", "comment", pl, true, function(r) {
        if (r.toLowerCase() == 'posted') {
            showMessage('Reply posted');
            var timeout = setTimeout(function() {
                $('#modal').removeClass('in');
                startInterval(1);
            }, 500);
        }
        else {
            showMessage('Errror: ' + r);
            var timeout = setTimeout(function() {
                $('#modal').removeClass('in');
                startInterval(1);
            }, 500);
        }
    });
    return false;
});

var curTaskId;
var curTaskTd;
$(document).on('click', '.done-icon.notcomplete', function(e) {
    $('.modal-title').html("Complete task");
    $('.modal-body').html(completeBox);
    completeTaskId = $(this).attr('taskid');

    $('.modal-backdrop').css('display', 'block');
    $('#modal').css('width', '380px');
    $('#modal').css('margin-left', '-190px');
    $('.modal-backdrop').addClass('in');
    $('.modal-backdrop').css('z-index', '9999');
    $('#modal').css('z-index', '10000');
    $('#modal').addClass("in");
    curTaskId = $(this).attr('taskid');
    curTaskTd = $(this).parent('td');
});

$(document).on('submit', '.widget-complete_form .bbf-form', function(e) {
    $(this).find('.commit').attr('disabled', 'disabled');
    $(this).find('.background-loading-small').removeClass('hide');
    taskAction = c2844_action.value;
    pl = new SOAPClientParameters();
    pl.add("id", curTaskId);
    pl.add("action", taskAction);
    SOAPClient.invoke("/m", "markComplete", pl, true, function(r) {
        if (curCompleteButton != undefined) {
            curCompleteButton.parents('.stream-task-container').addClass("completed");
            curCompleteButton.html("<i class=\"icon-complete-task\"></i> Undo Complete");
            text = curCompleteButton.parents('.stream-task-container').find(".mention-text").text();
            curCompleteButton.parents('.stream-task-container').find(".mention-text").text("Completed '" + text + "' with solution '" + taskAction + "'");
        }
        if (curTaskTd != undefined) {
            curTaskTd.prev().html('<span>' + taskAction + '</span>');
            curTaskTd.children('i').removeClass('notcomplete');
            curTaskTd.children('i').addClass('complete');
        }
        var timeout = setTimeout(function() {
            $('#modal').removeClass('in');
            startInterval(1);
        }, 500);

    });
    return false;
});

$(document).on('mouseenter', '.list-viewport>ul>li.unread', function(e) {
    var item = $(this);
    setTimeout(function() {
        item.removeClass("unread");
    }, 1000);
    var pl = new SOAPClientParameters();
    var streamId = $(this).attr('streamid');
    var threadId = $(this).attr('threadid');
    var messageId = $(this).attr('messageid');
    pl.add("streamId", streamId);
    pl.add("threadId", threadId);
    pl.add("messageId", messageId);
    SOAPClient.invoke("/m/", "markAsRead", pl, true, function(r) {
        //console.log(r);
    });
});


/* Task Manager actions
 * 
 * 
 * 
 */

$(document).on('mouseover', '.dataTable td', function(e) {
    var data = $(this).children('span').text().trim();
    if (data !== undefined && data != '') {
        $('#managerTips .tooltip-inner').html(data);
        var top = 20 + $(this).offset().top - $('.dataTable').offset().top + $('.search-content').offset().top + $(this).height() + $('.list-viewport').scrollTop();
        var left = $(this).offset().left + $(this).width() / 2 - $('.search-content').offset().left - $('#managerTips').width() / 2 - 5;
        $('#managerTips').css('top', top + 'px');
        $('#managerTips').css('left', left + 'px');
        $('#managerTips').css('display', 'block');
    }
    if ($(this).children('.tags').length == 0)
        $('#tagSelector').css('display', 'none');
    $('td.tdfocus').removeClass('tdfocus');
});
var curTag = '';
$(document).on('mouseover', '.dataTable td .tags', function(e) {
    var top = $(this).parent().offset().top - $('.dataTable').offset().top + $('.search-content').offset().top + $('.list-viewport').scrollTop() - 7;
    var left = $(this).offset().left + $(this).width() - $('.search-content').offset().left - 5;
    $('#tagSelector').css('top', top + 'px');
    $('#tagSelector').css('left', left + 'px');
    $('#tagSelector').css('display', 'block');
    $('#tagSelector').attr('taskid', $(this).attr('taskid'));
    curTag = $(this);

    var index = 0;
    var tagArray = new Array();
    $('#tagSelector li').attr('class', 'plus');
    curTag.children().each(function() {
        tagArray[index] = $(this).attr('title');
        $('#tagSelector li').each(function() {
            if ($(this).find('font').html() == tagArray[index]) {
                $(this).attr('class', 'minus');
            }
        });
        index++;
    });
    $(this).parent().addClass('tdfocus');
});

$(document).on('mouseleave', '.dataTable td', function(e) {
    $('#managerTips').css('display', 'none');
});

$(document).on('mouseover', '#tagSelector', function(e) {
    curTag.parents('td').attr('class', 'tdfocus');
});

$(document).on('mouseleave', '#tagSelector', function(e) {
    $('td.tdfocus').removeClass('tdfocus');
});

$(document).on('click', '#tagSelector li', function(e) {
    var tagId = $(this).attr('data-id');
    var taskId = $('#tagSelector').attr('taskid');
    var pl = new SOAPClientParameters();
    pl.add('taskId', taskId);
    pl.add('tagId', tagId);
    if ($(this).attr('class') == 'plus') {
        SOAPClient.invoke("/m", "addTagofTask", pl, true, function(r) {
            if (r != 'failed') {
                var firstChar = r.substring(0, 1);
                curTag.append('<span class="' + firstChar + '" title="' + r + '">' + firstChar + '</span>');
            }
        });
        $(this).attr('class', 'minus');
    }
    else {
        SOAPClient.invoke("/m", "removeTagofTask", pl, true, function(r) {
            if (r != 'failed') {
                curTag.children().each(function() {
                    if ($(this).attr('title') == r)
                        $(this).remove();
                });
            }
        });
        $(this).attr('class', 'plus');
    }
    return false;
});

/* end task manager action
 * 
 */

/*
 * Search in stream
 */
var timerSearchInStream = undefined;
$(document).on('keyup', '#doSearchInStream', function(e) {
    if ($(this).val() == '') {
        $('.searchBox .clear-icon').css('display', 'none');
    }
    else {
        $('.searchBox .clear-icon').css('display', 'block');
    }
    clearInterval(timerSearchInStream);
    timerSearchInStream = setTimeout(function() {
        searchInStream($('#doSearchInStream').val());
    }, 1000);
});

function searchInStream(keyword) {
    $('.searched').removeClass('.searched');
    $('.highlight').removeClass('highlight');
    //reset
    if (keyword == '') {
        $('ul.widget-signals>li').each(function() {
            mention = $(this).find('.mention-text');
            mention.html(mention.attr('text'));
            title = $(this).find('.mention-title');
            title.html(title.attr('text'));
            source = $(this).find('.mention-short-url a').first();
            source.html(source.attr('text'));
            author = source.next();
            author.html(author.attr('text'));
            $(this).show();
            replies = $(this).find('.mention-top-bar');
            if (replies.length > 0) {
                replies.each(function() {
                    var replyContent = $(this).find('.main-reply-content');
                    replyContent.html(replyContent.attr('text'));
                    if (!$(this).hasClass('hide'))
                        $(this).show();
                });
            }
        });
        return;
    }
    $('ul.widget-signals>li').each(function() {
        //reset before searching
        title = $(this).find('.mention-title');
        title.html(title.attr('text'));
        source = $(this).find('.mention-short-url a').first();
        source.html(source.attr('text'));
        author = source.next();
        author.html(author.attr('text'));

        var re = new RegExp('(' + keyword + ')(?=[^>]*(<|$))', "gi");
        mention = $(this).find('.mention-text');
        mention.html(mention.attr('text'));

        //search in title
        var matchTitle = false;
        titleText = title.html();
        if (titleText.search(re) !== -1) {
            titleText = titleText.replace(re, '<span class="highlight">$1</span>');
            title.html(titleText);
            matchTitle = true;
        }

        //search in author
        var matchAuthor = false;
        authorText = author.html();
        if (authorText.search(re) !== -1) {
            authorText = authorText.replace(re, '<span class="highlight">$1</span>');
            author.html(authorText);
            matchAuthor = true;
        }

        //search in source
        var matchSource = false;
        sourceText = source.html();
        if (sourceText.search(re) !== -1) {
            sourceText = sourceText.replace(re, '<span class="highlight">$1</span>');
            source.html(sourceText);
            matchSource = true;
        }

        //search all text in lead
        var text = $(this).find('.mention-text').html();
        var textMatch = false;
        if (text != undefined)
            if (text.search(re) !== -1) {
                //found something
                textMatch = true;
                text = text.replace(re, '<span class="highlight">$1</span>');
                $(this).find('.mention-text').html(text);
                $(this).show();
                if ($(this).find('.readmore-content.hide').html() != undefined)
                    if ($(this).find('.readmore-content.hide').html().search(re) !== -1) {
                        if (!matchTitle && !matchAuthor && !matchSource)
                            $(this).find('.readmore.spanshow:not(.hide)').addClass('highlight');
                    }
                mention.addClass('searched');
            }
        //search all replies
        replies = $(this).find('.main-reply-content p');
        var match = false;
        if (replies.length > 0) {
            replies.each(function() {
                var replyContent = $(this).find('.main-reply-content');
                replyContent.html(replyContent.attr('text'));
                var replyText = $(this).html();
                if (replyText.search(re) !== -1) {
                    replyText = replyText.replace(re, '<span class="highlight">$1</span>');
                    $(this).html(replyText);
                    $(this).parents('.mention-top-bar').show();
                    match = true;
                    if ($(this).find('.readmore-content.hide').html() != undefined)
                        if ($(this).find('.readmore-content.hide').html().search(re) !== -1) {
                            if (!matchTitle && !matchAuthor && !matchSource)
                                $(this).find('.readmore.spanshow:not(.hide)').addClass('highlight');
                        }
                }
                else {
                    if (!matchAuthor && !matchSource)
                        $(this).parents('.mention-top-bar').hide();
                }
                $(this).addClass('searched');
            });
        }
        if ((!match && !textMatch) && !matchTitle && !matchAuthor && !matchSource) {
            $(this).hide();
        }
    });
}

$(document).on('click', '.searchBox .clear-icon', function(e) {
    $('.searchBox .clear-icon').css('display', 'none');
    $('#doSearchInStream').val('');
    searchInStream('');
});

/* send via email & sms */
var curTitle = '';
$(document).on('click', '.send-action-tab .send-menu', function() {
    curSendButton = $(this);
    if ($(this).hasClass('marked')) {
        var later = $('#sendMenu li.email-later');
        later.find('font').html('Marked for sending later');
        later.find('i').addClass('flaged').removeClass('unflaged');
    }
    else {
        var later = $('#sendMenu li.email-later');
        later.find('font').html('Mark for sending later');
        later.find('i').addClass('unflaged').removeClass('flaged');
    }
    var left = $(this).offset().left + $(this).width() - $('#sendMenu').width() - $(this).parents('.widget-story_signal').offset().left;
    var top = $(this).offset().top + $(this).height() + $('.list-viewport').scrollTop();
    $('#sendMenu').css('left', left + 'px');
    $('#sendMenu').css('top', top + 'px');
    $('#sendMenu').css('display', 'block');
    curContent = $(this).attr('content');
    curTitle = $(this).attr('threadtitle');
    curThreadId = $(this).attr('threadid');
    curMessageId = $(this).attr('messageid');
    curStreamId = $(this).parents('.widget-story_signal').attr('streamid');
    var mentionCore = $(this).parents('.mention-core');
    curSource = mentionCore.find('.mention-short-url .action-color-active').first().text();
    curDate = mentionCore.find('.signals-additional-time')
    var orgText = mentionCore.find('.mention-text')[0].innerText;
    curText = orgText.replace('Read more', '').trim();
    var date = new Date(mentionCore.find('.signals-additional-time').text());
    var dateData = getDatenTime(date);
    curDate = dateData[0];
    curTime = dateData[1];
    curLink = mentionCore.find('.mention-title a').attr('href');
});

$(document).on('mouseleave', '#sendMenu', function() {
    $(this).css('display', 'none');
    $('#sendMenu .email-later, #sendMenu .email-immediately').slideUp(0);
});

$(document).on('mouseover', '#sendMenu .email', function() {
    $('#sendMenu .email-later, #sendMenu .email-immediately').slideDown(200);
});

$(document).on('click', '#sendMenu li', function() {
    var li = $(this);
    switch ($(this).attr('class')) {
        case 'email':
            break;
        case 'sms':
            $('.modal-title').html("Send SMS");
            $('.modal-body').html(sendSMSBox);
            $('.modal-backdrop').css('display', 'block');
            $('#modal').css('width', '350px');
            $('#modal').css('margin-left', '-175px');
            $('.modal-backdrop').addClass('in');
            $('.modal-backdrop').css('z-index', '9999');
            $('#modal').css('z-index', '10000');
            $('#modal').addClass("in");
            $('#c2844_sms').text(curContent);
            break;
        case 'email-later':
            if (!li.find('i').hasClass('flaged')) {
                var pl = new SOAPClientParameters();
                pl.add('messageId', curMessageId);
                pl.add('streamId', curStreamId);
                pl.add('post', '<a href="' + curLink + '" target="_blank">' + curText + '</a>');
                pl.add('action', curTitle);
                SOAPClient.invoke('/m', 'markForSendingLater', pl, true, function(r) {
                    if (r == 'succeed') {
                        li.find('font').html('Marked for sending later');
                        li.find('i').addClass('flaged').removeClass('unflaged');
                        curSendButton.addClass('marked');
                    }
                });
            }
            break;
        case 'email-immediately':
            $('.modal-title').html("Send email");
            $('.modal-body').html(sendEmailBox);
            $('.modal-backdrop').css('display', 'block');
            $('#modal').css('width', '640px');
            $('#modal').css('margin-left', '-320px');
            $('.modal-backdrop').addClass('in');
            $('.modal-backdrop').css('z-index', '9999');
            $('#modal').css('z-index', '10000');
            $('#modal').addClass("in");
            curText = curText.replace('show quote ', '');
            var endPos = curText.indexOf(' ', 200);
            if (endPos != -1)
                curText = curText.substring(0, endPos);
            emailSubject.value = curTitle;
            editor = new nicEditor({buttonList: ['bold', 'italic', 'underline', 'forecolor', 'fontSize', 'left', 'center', 'right', 'html'], maxHeight: 200}).panelInstance('c2844_description');
            $('.nicEdit-main').html('<p>An alert has been triggered for the following post on ' + curSource + ':</p>\
                            <p><strong>' + curTitle.replace('[BUZZMETRICS ALERT] ', '') + '</strong><br>Link: <a href="' + curLink + '">' + curLink + '</a><br>\
                            \'' + curText + '\'<br><i>' + curDate + ' at ' + curTime + '</i></p><p>\
                            Buzzmetrics Team</p><p>You have subscribed to Buzzmetrics real-time social media monitoring and alert. To turn this alert off, please login to your account at http://pulse.buzzmetrics.vn or contact your account manager for support.</p>');
            break;
    }
});

var editor, curContent = '';

//Task
$(document).on('click', '.email.notcomplete', function() {
    $('.modal-title').html("Send email");
    $('.modal-body').html(sendEmailBox);
    $('.modal-backdrop').css('display', 'block');
    $('#modal').css('width', '640px');
    $('#modal').css('margin-left', '-320px');
    $('.modal-backdrop').addClass('in');
    $('.modal-backdrop').css('z-index', '9999');
    $('#modal').css('z-index', '10000');
    $('#modal').addClass("in");
    emailSubject.value = $(this).parent().prev().text();
    editor = new nicEditor({buttonList: ['bold', 'italic', 'underline', 'forecolor', 'fontSize', 'left', 'center', 'right', 'html'], maxHeight: 200}).panelInstance('c2844_description');
    var pl = new SOAPClientParameters();
    pl.add('taskIds', $(this).attr('taskid'));
    SOAPClient.invoke("/m", "getMailHTML", pl, true, function(r) {
        $('.nicEdit-main').html(unescapeHtml(r));
    });
});

function escapeHtml(text) {
    return text
            .replace(/&/g, "&amp;")
            .replace(/</g, "&lt;")
            .replace(/>/g, "&gt;")
            .replace(/"/g, "&quot;")
            .replace(/'/g, "&#039;");
}

function unescapeHtml(text) {
    return text
            .replace(/&amp;/g, "&")
            .replace(/&lt;/g, "<")
            .replace(/&gt;/g, ">")
            .replace(/&quot;/g, "\"")
            .replace(/&#039;/g, "'");
}

$(document).on('click', '.sms.notcomplete', function() {
    $('.modal-title').html("Send SMS");
    $('.modal-body').html(sendSMSBox);
    $('.modal-backdrop').css('display', 'block');
    $('#modal').css('width', '350px');
    $('#modal').css('margin-left', '-175px');
    $('.modal-backdrop').addClass('in');
    $('.modal-backdrop').css('z-index', '9999');
    $('#modal').css('z-index', '10000');
    $('#modal').addClass("in");
    curContent = $(this).parent().prev().text();
    var phoneNumbers = curContent.substring(1, curContent.indexOf(' ') - 2).split(';');
    curContent = curContent.substring(curContent.indexOf(' ') + 1);
    for (i = 0; i < phoneNumbers.length; i++)
        $('.data-presenting span:last-child').before('<span class="sms" email="' + phoneNumbers[i] + '">' + phoneNumbers[i] + '<i class="clear-icon"></i></span>')
    $('#c2844_sms').text(curContent);
});
/* end send via email & sms */


/* tags input */
$(document).on('mousemove', '.suggest-input .dropdown-menu li', function() {

});

$(document).on('mouseover', '.suggest-input .dropdown-menu li', function() {
    $('.suggest-input .dropdown-menu li.active').removeClass('active');
    $(this).addClass('active');
    selectedCoaddClassntact = $(this).attr('data-id');
    currentContact = $(this);
});

$(document).on('click', '.suggest-input .dropdown-menu li', function() {
    if (!$(this).hasClass('active')) {
        $('.suggest-input .dropdown-menu li.active').removeClass('active');
        $(this).addClass('active');
    }
    var input = $(this).parents('.suggest-input').find('input');
    //var text = input.val();
    //text += $(this).text().trim() + '; ';
    input.val('');
    input.focus();
    var email = $(this).attr('email');
    var name = $(this).attr('name');
    input.parent().before('<span class="email" email="' + email + '">' + name + '<i class="clear-icon"></i></span>');
    var wrapper = $(this).parents('.suggest-input');
    var dropbox = input.parent().parent().next();
    var top = wrapper.height();
    dropbox.css('top', top + 'px');
});

$(document).on('focus', '.suggest-input input', function() {
    $(this).attr('placeholder', '');
    var wrapper = $(this).parents('.suggest-input');
    var dropbox = $(this).parent().parent().next();
    var left = 0;
    var top = wrapper.height();
    dropbox.css('left', left + 'px');
    dropbox.css('top', top + 'px');
    dropbox.css('display', 'block');
    dropbox.find('li.active').removeClass('active');
    dropbox.find('li').first().addClass('active');
    currentContact = $('.suggest-input .dropdown-menu ul li').first();
    $(this).parent().parent().addClass('focus');
});

$(document).on('blur', '.suggest-input input', function() {
    $(this).css('width', (($(this).val().length + 1) * 7.3) + 'px');
    var wrapper = $(this).parents('.suggest-input');
    var dropbox = $(this).parent().parent().next();
    var input = $(this);
    var email = $(this).val();
    input.css('width', ((input.val().length + 1) * 7.3) + 'px');
    if (email !== '') {
        if (email.indexOf(',') !== -1) {
            values = email.split(',');
            for (i = 0; i < values.length; i++) {
                if (values[i] !== '')
                    $(this).parent().before('<span class="email" email="' + values[i] + '">' + values[i] + '<i class="clear-icon"></i></span>');
            }
        }
        else
            $(this).parent().before('<span class="email" email="' + email + '">' + email + '<i class="clear-icon"></i></span>');
        $(this).val('');
    }
    setTimeout(function() {
        if ($('.suggest-input input').is(':focus') == false) {
            dropbox.css('display', 'none');
            input.parent().parent().removeClass('focus');
        }
    }, 100);
});

var selectedContact = 0;
var currentContact;

$(document).on('keydown', '.suggest-input input', function(e) {
    var keyCode = e.keyCode;
    var dropbox = $(this).parent().parent().next();
    $(this).css('width', (($(this).val().length + 1) * 7.3) + 'px');
    if (keyCode !== 13) {
        dropbox.find('li.active').removeClass('active');
    }
    if (keyCode === 38 || keyCode === 40) {
        //38 Up arrow
        //40 Down arrow
        var allLi = $('.suggest-input .dropdown-menu ul li');
        allLi.each(function() {
            if ($(this).attr('data-id') === selectedContact) {
                currentContact = $(this);
                return;
            }
        })
        if (keyCode === 38) {
            if (currentContact.prev().length !== 0) {
                currentContact = currentContact.prev();
                while (currentContact.hasClass('hide'))
                    currentContact = currentContact.prev();
            }
        }
        if (keyCode === 40) {
            if (currentContact.next().length !== 0) {
                currentContact = currentContact.next();
                while (currentContact.hasClass('hide'))
                    currentContact = currentContact.next();
            }
        }
        var contactCount = dropbox.find('li').length;
        currentContact.addClass('active');
        return false;
    } else if (keyCode === 13) {
        $('.suggest-input .dropdown-menu ul li.active').click();
        $(this).focus();
        return false;
    } else if (keyCode === 186 || keyCode === 188) {
        //Add custom email
        var email = $(this).val();
        if (email !== '') {
            $(this).parent().before('<span class="email" email="' + email + '">' + email + '<i class="clear-icon"></i></span>');
            $(this).val('');
        }
        return false;
    }
    if (keyCode === 8) { //backspace
        if ($(this).val() === '') {
            //select last tag
            var activeSpan = $(this).parents('.data-presenting').children('.active');
            if (activeSpan.length === 0)
                $(this).parent().prev().addClass('active');
            else
                activeSpan.children('i').click();
        }
    }
});

$(document).on('keyup', '.suggest-input input', function(e) {
    //search contact
    if (e.keyCode === 38 || e.keyCode === 40)
        return false;
    var val = $(this).val();
    if (val === '') {
        $('.suggest-input .dropdown-menu ul li').each(function() {
            $(this).removeClass('hide');
        });
    }
    else {
        $('.suggest-input .dropdown-menu ul li').each(function() {
            var re = new RegExp(val, "i");
            if ($(this).text().search(re) === -1)
                $(this).addClass('hide');
            else
                $(this).removeClass('hide');
        });
    }
    currentContact = $('.suggest-input .dropdown-menu ul li:not(.hide)').first();
    currentContact.addClass('active');
});

$(document).on('click', '.data-presenting', function(e) {
    $(this).find('input').focus();
})

$(document).on('click', '.data-presenting span i', function(e) {
    $(this).parent().remove();
});
/* end tags input */

/* task manager filter */
$(document).on('click', '#task-manager', function(e) {
    $(this).find('.active-section').removeClass('active-section');
})

$(document).on('click', '#task-manager li', function(e) {
    $('#task-manager li.active-section').removeClass('active-section');
    $('#controller-container').animate({'opacity': 0.1});
    var curLi = $(this);
    var type = $(this).text().trim();
    if (curRequest !== undefined)
        curRequest.abort();
    curRequest = $.post('/activity/manager/mainview/?filter=' + type, function(data) {
        $('#controller-container').html(data);
        curLi.addClass('active-section');
        $('#controller-container').animate({'opacity': 1});
    });
});

$(document).on('change', 'input[name=checkAll]', function() {
    cb = $(this);
    $('input[type=checkbox]').prop('checked', cb.prop('checked'));
});

$(document).on('click', '#doWithAll', function(e) {
    var taskIds = '';
    $('#taskList input:checked:not(first-child)').each(function(e) {
        if ($(this).attr('taskid') !== undefined)
            taskIds += $(this).attr('taskid') + ';';
    });
    var actionName = $(this).text().trim();
    switch (actionName.toUpperCase()) {
        case "SEND EMAIL":
            $('.modal-title').html("Send email");
            $('.modal-body').html(sendEmailBox);
            $('.modal-backdrop').css('display', 'block');
            $('#modal').css('width', '640px');
            $('#modal').css('margin-left', '-320px');
            $('.modal-backdrop').addClass('in');
            $('.modal-backdrop').css('z-index', '9999');
            $('#modal').css('z-index', '10000');
            $('#modal').addClass("in");
            if ($('#taskList input:checked').length > 1)
                emailSubject.value = "[BUZZMETRICS ALERT] Please take a look at these discussions on social media";
            else
                emailSubject.value = $('#taskList input:checked').parents('tr').children('td')[7].innerText;
            editor = new nicEditor({buttonList: ['bold', 'italic', 'underline', 'forecolor', 'fontSize', 'left', 'center', 'right', 'html'], maxHeight: 200}).panelInstance('c2844_description');
            var pl = new SOAPClientParameters();
            pl.add('taskIds', taskIds);
            SOAPClient.invoke("/m", "getMailHTML", pl, true, function(r) {
                $('.nicEdit-main').html(unescapeHtml(r));
            });
            break;
        case "MARK AS READ":

            break;
    }

});

/* end task manager filter */

/* invite users */
$(document).on('click', '.widget-invite_users_button a', function() {
    $('.modal-title').html("Invite User");
    $('.modal-body').html(sendInvitationBox);
    $('.modal-backdrop').css('display', 'block');
    $('#modal').css('width', '400px');
    $('#modal').css('margin-left', '-200px');
    $('.modal-backdrop').addClass('in');
    $('.modal-backdrop').css('z-index', '9999');
    $('#modal').css('z-index', '10000');
    $('#modal').addClass("in");
});

$(document).on('submit', '.widget-invite_form .bbf-form', function(e) {
    $(this).find('.commit').attr('disabled', 'disabled');
    $(this).find('.background-loading-small').removeClass('hide');
    var name = inviteName.value;
    var email = inviteEmail.value;
    var phone = invitePhone.value;
    var title = inviteTitle.value;
    var emailRe = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    var phoneRe = /^(\+|\d)[0-9]{7,16}$/;
    if (emailRe.test(email) && phoneRe.test(phone) && title !== '' && name !== '') {
        //Add user
        var pl = new SOAPClientParameters();
        pl.add("typedata", "user");
        pl.add("email", email);
        pl.add("password", 'a2452fba805dad71c12daeb96a0ae40b');
        pl.add("fullname", name);
        pl.add("company", $(this).attr('company'));
        pl.add("address", 'Ho Chi Minh');
        pl.add("phone", phone);
        pl.add("position", title);
        pl.add("dateregistered", '');
        pl.add("token", '');
        pl.add("timezone", '');
        SOAPClient.invoke("/m/", "addUser", pl, true, function(r) {
            if (r == "true") {
                showMessage('Invitation has been sent to: ' + email);
                var timeout = setTimeout(function() {
                    $('#modal').removeClass('in');
                    startInterval(1);
                }, 500);
                var pl = new SOAPClientParameters();
                SOAPClient.invoke("/m/", "getUser", pl, true, getuser_callback);
                $.post("/ajax/sendEmailBox", function(data) {
                    sendEmailBox = data;
                });
                $.post("/ajax/sendSMSBox", function(data) {
                    sendSMSBox = data;
                });
                $.post("/ajax/addTask", function(data) {
                    addTask = data;
                });
            }
        });
    }
    return false;
});
/* end invite users */


function getTrueDate(date) {
    var day = String("0" + date.getDate()).slice(-2);
    var month = String("0" + (date.getMonth() + 1)).slice(-2);
    var year = date.getFullYear();
    return day + '-' + month + '-' + year;
}

function getDisplayDate(date) {
    var day = String("0" + date.getDate()).slice(-2);
    var month = parseMonth(date.getMonth());
    return month + ' ' + day;
}


function parseMonth(month) {
    switch (month) {
        case 0:
            return "Jan";
        case 1:
            return "Feb";
        case 2:
            return "Mar";
        case 3:
            return "Apr";
        case 4:
            return "May";
        case 5:
            return "Jun";
        case 6:
            return "Jul";
        case 7:
            return "Aug";
        case 8:
            return "Sep";
        case 9:
            return "Oct";
        case 10:
            return "Nov";
        case 11:
            return "Dec";

    }
}

/* auto load */

var autoLoadTimer = setInterval(function() {
    if ($('ul.widget-signals').html() != '' && !pause)
        if ($('ul.widget-signals').height() < $('.list-viewport').height() || $('.list-viewport').height() + $('.list-viewport').scrollTop() > $('ul.widget-signals').height() - 100) {
            $('.list-viewport').scroll();
        }
}, 500);

/* end auto load */

/* comparison */

$(document).on('click', '#sov-mentions-widget .hourly-filter-wrapper li', function() {
    if ($('#sov-notice').text().trim() !== 'NOT ENOUGH DATA TO SHOW. PLEASE TRY AGAIN LATER.') {
        if ($(this).hasClass('selected')) {
            if (colLabelFormat === '{point.percentage:.1f}%') {
                colLabelFormat = '';
            }
            else {
                colLabelFormat = '{point.percentage:.1f}%';
            }
        }
        var selected = $('#sov-mentions-widget .hourly-filter-wrapper .selected');
        selected.removeClass('selected');
        selected.addClass('not_selected');
        $(this).removeClass('not_selected');
        $(this).addClass('selected');
        loadSOV();
    }
});

$(document).on('click', '#trend-mentions-widget .hourly-filter-wrapper li', function() {
    if ($('#trend-notice').text().trim() !== 'NOT ENOUGH DATA TO SHOW. PLEASE TRY AGAIN LATER.') {
        if ($(this).hasClass('selected')) {
            if (colTrendLabelFormat === '{point.percentage:.1f}%') {
                colTrendLabelFormat = '';
            }
            else {
                colTrendLabelFormat = '{point.percentage:.1f}%';
            }
        }
        var selected = $('#trend-mentions-widget .hourly-filter-wrapper .selected');
        selected.removeClass('selected');
        selected.addClass('not_selected');
        $(this).removeClass('not_selected');
        $(this).addClass('selected');
        loadTrend();
    }
});

/* end comparison */

/* tag groups */
var currentGroup, groupid;
$(document).on('click', '#grouplist .expand-folder:not(.folder-fade)', function(e) {
    groupid = $(this).parent().attr('data-id');
    $('#all-groups').removeClass('expanded-folder');
    $('#grouplist .expanded-folder').removeClass('expanded-folder');
    $(this).addClass('expanded-folder');
    $('.tags-view .stream-title span').text($(this).children('span').text().split('(')[0].trim());
    var pl = new SOAPClientParameters();
    pl.add('groupId', groupid);
    SOAPClient.invoke("/m/", "listTag", pl, true, listtag_callback);
    $('.add_tag').last().css('display', '');

});
function listtag_callback(r) {
    if (r !== 'null') {
        var tags = JSON.parse(r);
        $('div.mozaic-widget.widget-list ul').empty();
        for (i = 0; i < tags.length; i++) {
            var keywords = '';
            if (tags[i].keywords !== '')
                keywords = '<span class="keywords" style="margin-left: 25px;color: #AAA;display: block;margin-top: -13px;">' + tags[i].keywords + '</span>';
            var li = '<li class="mozaic-widget item-1000031974 folder-tab first widget-stream_item">' +
                    '<div>' +
                    '<a class="expand-folder type-keyword">' +
                    '<i class="icon-stream-type icon-stream-market_terms-small"></i><span>' + tags[i].tagName + '</span>' + keywords +
                    '</a>';
            /*if (tags[i].editable) {
             li += '<div class="buttons-container small">' +
             '<div class="btn-holder edit-button">' +
             '<a data-id="' + tags[i].tagId + '" groupid="' + tags[i].groupId + '" data-context="market_terms" data-type="keyword" class="edit-button btn btn-small">' +
             '<i class="icon-edit"></i><span>Edit</span>' +
             '</a>' +
             '</div>' +
             '<div class="btn-holder delete-button">' +
             '<a data-id="' + tags[i].tagId + '" groupid="' + tags[i].groupId + '" data-type="keyword" class="insert-delete-form delete-button btn btn-small">' +
             '<i class="icon-delete-folder"></i><span>Delete</span>' +
             '</a>' +
             '</div>' +
             '</div>' +
             '</div>' +
             '</li>';
             }*/
            $('div.mozaic-widget.widget-list ul').append(li);
        }
    }
    else {
        $('div.mozaic-widget.widget-list ul').empty();
    }
}

$(document).on('click', '#all-groups', function(e) {
    $(this).parent().parent().find('.expanded-folder').removeClass('expanded-folder');
    $(this).addClass('expanded-folder');
    $('#stream-title').text($(this).text().trim());
    var pl = new SOAPClientParameters();
    pl.add('groupId', 0);
    SOAPClient.invoke("/m/", "listTag", pl, true, listtag_callback);
    $('.add_tag').last().css('display', 'none');
});

function renderGroup() {
    for (i = 0; i < groups.length; i++) {
        var html = '<li data-id="' + groups[i].groupid + '" class="mozaic-widget folder-tab widget-folder_item">\
            <a id="folder-tab" class="expand-folder">\
                <i class="icon-folder"></i><span>' + groups[i].groupname + '</span>\
            </a>';
        /*if (groups[i].userid == currentUserId)
         html += '<a class="edit-folder" style="display: none; background-color: transparent!important;">\
         <input id="foldername" name="foldername" placeholder="Your Folder" type="text" style="width: 145px;">\
         <input class="btn btn-red" id="btn-save" type="submit" value="Save">\
         </a>\
         <div class="buttons-container small" style="right: 66px">\
         <div class="btn-holder edit-button">\
         <a taggroup="' + groups[i].groupid + '" class="edit-button btn btn-small" style="position: initial;">\
         <i class="icon-edit"></i><span>Edit</span>\
         </a>\
         </div>\
         </div>\
         <div class="buttons-container small">\
         <div class="btn-holder delete-button">\
         <a taggroup="' + groups[i].groupid + '" class="delete-button btn btn-small" style="position: initial;">\
         <i class="icon-delete"></i><span>Delete</span>\
         </a>\
         </div>\
         </div>';*/
        html += '</li>';
        $('ul#grouplist').append(html);
    }

}

/* end tag groups */

/* engagement */

function loadTopSources() {
    if (window.location.href.split('#')[1].split('/')[0].toLowerCase() !== 'engagement')
        return;
    $('.widget-top_source').parent().parent().removeClass('loaded');
    var streamId = window.location.href.split('#')[1].split('/')[1];
    streamId = window.location.href.split('#')[1].split('/')[1];
    dateFrom = $('#selected_date').attr('datefrom');
    dateTo = $('#selected_date').attr('dateto');
    language = $('#language-filter-widget a').first().attr('data-value');
    tags = $('#tag-filter-widget a').first().attr('data-value');
    sentiment = $('.radio-options-sentiment .selected').attr('data-value');
    type = $('#platform-filter-widget').find('a').attr('data-value');
    var data = JSON.stringify({'dateFrom': dateFrom, 'dateTo': dateTo, 'language': language, 'type': type});
    $.post("ws/topsources/" + streamId + "/" + data, function(data) {
        $('#top-source-inner').html(data);
        $('.widget-top_source').parent().animate({'opacity': 1}, 500);
        $('.widget-top_source').parent().parent().addClass('loaded');
        $('#tableTopSources').dataTable({
            "sPaginationType": "full_numbers"
        });
    });
}

function loadTopAuthors() {
    if (window.location.href.split('#')[1].split('/')[0].toLowerCase() !== 'engagement')
        return;
    $('.widget-top_author').parent().parent().removeClass('loaded');
    var streamId = window.location.href.split('#')[1].split('/')[1];
    streamId = window.location.href.split('#')[1].split('/')[1];
    dateFrom = $('#selected_date').attr('datefrom');
    dateTo = $('#selected_date').attr('dateto');
    language = $('#language-filter-widget a').first().attr('data-value');
    tags = $('#tag-filter-widget a').first().attr('data-value');
    sentiment = $('.radio-options-sentiment .selected').attr('data-value');
    type = $('#platform-filter-widget').find('a').attr('data-value');
    var data = JSON.stringify({'dateFrom': dateFrom, 'dateTo': dateTo, 'language': language, 'type': type});
    $.post("ws/topauthors/" + streamId + "/" + data, function(data) {
        $('#top-author-inner').html(data);
        $('.widget-top_author').parent().animate({'opacity': 1}, 500);
        $('.widget-top_author').parent().parent().addClass('loaded');
        $('#tableTopAuthors').dataTable({
            "sPaginationType": "full_numbers"
        });
    });
}

function loadTopThreads() {
    if (window.location.href.split('#')[1].split('/')[0].toLowerCase() !== 'engagement')
        return;
    $('.widget-top_thread').parent().parent().removeClass('loaded');
    var streamId = window.location.href.split('#')[1].split('/')[1];
    streamId = window.location.href.split('#')[1].split('/')[1];
    dateFrom = $('#selected_date').attr('datefrom');
    dateTo = $('#selected_date').attr('dateto');
    language = $('#language-filter-widget a').first().attr('data-value');
    tags = $('#tag-filter-widget a').first().attr('data-value');
    sentiment = $('.radio-options-sentiment .selected').attr('data-value');
    type = $('#platform-filter-widget').find('a').attr('data-value');
    var data = JSON.stringify({'dateFrom': dateFrom, 'dateTo': dateTo, 'language': language, 'type': type});
    $.post("ws/topthreads/" + streamId + "/" + data, function(data) {
        $('#top-thread-inner').html(data);
        $('.widget-top_thread').parent().animate({'opacity': 1}, 500);
        $('.widget-top_thread').parent().parent().addClass('loaded');
        $('#tableTopThreads').dataTable({
            "sPaginationType": "full_numbers"
        });
    });
}

function loadEngagement() {
    loadTopSources();
    loadTopAuthors();
    loadTopThreads();
}
/* end engagement */

/* sentiment scoring */
var curButton;
$(document).on('click', '.sentiment-score button', function() {
    var messageId = $(this).parent().attr('messageid');
    var threadId = $(this).parent().attr('threadid');
    var score = $(this).attr('score');
    var pl = new SOAPClientParameters();
    var type = $(this).parent().attr('type');
    var source = $(this).parent().attr('source');
    pl.add('messageId', messageId);
    pl.add('threadId', threadId);
    pl.add('score', score);
    var timeBlock = $(this).parent().prev().find('.signals-additional-time');
    if (timeBlock.length === 0)
        timeBlock = $(this).parent().prev().prev().find('.signals-additional-time');
    dateString = timeBlock.text();
    pl.add('dateCreated', dateString);
    tstreamId = Base64.decode(window.location.href.split('#')[1].split('/')[1]);
    pl.add('streamId', tstreamId);
    pl.add('type', type);
    pl.add('source', source);
    curButton = $(this);
    SOAPClient.invoke("/m/", "changeSentiment", pl, true, function(r) {
        if (r == 'succeed') {
            curButton.parent().children('button').removeAttr('disabled');
            curButton.attr('disabled', 'disabled');
            var color = '#EEE';
            if (parseInt(curButton.attr('score')) == 0)
                color = '#9bbb59';
            else if (parseInt(curButton.attr('score')) > 0)
                color = '#4f81bd';
            else if (parseInt(curButton.attr('score')) === -1)
                color = '#c0504d';
            else
                color = '#ffe563';
            curButton.parent().css('background', color);
        }
    });
});
/* end scoring */

/* tag group */
$(document).on('click', '.new-tag-group', function() {
    $('.modal-title').html("New Group");
    $('.modal-body').html(addTagGroup);

    $('.modal-backdrop').css('display', 'block');
    $('#modal').css('width', '380px');
    $('#modal').css('margin-left', '-190px');
    $('.modal-backdrop').addClass('in');
    $('.modal-backdrop').css('z-index', '9999');
    $('#modal').css('z-index', '10000');
    $('#modal').addClass("in");
});

$(document).on('submit', '.widget-addgroup_form .bbf-form', function(e) {
    $('.submit-form .commit').attr('disabled', 'disabled');
    var helpBlock = $('.widget-addgroup_form .help-block');
    helpBlock.css('color', '');
    helpBlock.text('Name your tag group');
    //Add tag group
    var tagGroupName = document.getElementById('tagGroupName').value;
    var pl = new SOAPClientParameters();
    if ($('.submit-form .commit').attr('id') == undefined) {
        pl.add("groupName", tagGroupName);
        SOAPClient.invoke("/m/", "addTagGroup", pl, true, function(r) {
            if (r !== 'null' && r !== 'duplicate') {
                var group = JSON.parse(r);
                $('ul#grouplist').append('<li data-id="' + group.id + '" class="mozaic-widget folder-tab widget-folder_item">\
                                    <a id="folder-tab" class="expand-folder">\
                                    <i class="icon-folder"></i><span>' + group.name + '</span>\
                                    </a>\
            <!--<div class="buttons-container small" style="right: 66px">\
                <div class="btn-holder edit-button">\
                    <a taggroup="' + group.id + '" class="edit-button btn btn-small" style="position: initial;">\
                        <i class="icon-edit"></i><span>Edit</span>\
                    </a>\
                </div>\
            </div>\
            <div class="buttons-container small">\
                <div class="btn-holder delete-button">\
                    <a taggroup="' + group.id + '" class="delete-button btn btn-small" style="position: initial;">\
                        <i class="icon-delete"></i><span>Delete</span>\
                    </a>\
                </div>\
            </div>--></li>');
                var timeout = setTimeout(function() {
                    $('#modal').removeClass('in');
                    startInterval(1);
                }, 500);
            }
            else {
                if (r === 'duplicate') {
                    var helpBlock = $('.widget-addgroup_form .help-block');
                    helpBlock.css('color', 'red');
                    helpBlock.text('Group \'' + tagGroupName + '\' has already been taken.');
                    $('.submit-form .commit').removeAttr('disabled');
                }
            }
        });
    }
    else {
        pl.add('groupId', $('.submit-form .commit').attr('id'));
        pl.add("groupName", tagGroupName);
        SOAPClient.invoke("/m/", "modifyGroup", pl, true, function(r) {
            if (r == 'succeed') {
                curGroup.find('a#folder-tab span').text(tagGroupName);
                if (curGroup.children('a').hasClass('expanded-folder')) {
                    $('.tags-view .stream-title span').text(tagGroupName);
                }
                var timeout = setTimeout(function() {
                    $('#modal').removeClass('in');
                    startInterval(1);
                }, 500);
            }
        });
    }
    return false;
});

/** add tag **/
$(document).on('click', '.new-tag', function() {
    $('.modal-title').html("New Tag");
    $('.modal-body').html(addTag);

    $('.modal-backdrop').css('display', 'block');
    $('#modal').css('width', '380px');
    $('#modal').css('margin-left', '-190px');
    $('.modal-backdrop').addClass('in');
    $('.modal-backdrop').css('z-index', '9999');
    $('#modal').css('z-index', '10000');
    $('#modal').addClass("in");
});

$(document).on('submit', '.widget-addtag_form .bbf-form', function(e) {
    //Add tag group
    var tagName = document.getElementById('ftagName').value;
    if (tagName === '') {
        $('.help-block').first().css('color', 'red');
        return false;
    }
    else
        $('.help-block').first().css('color', '');
    $('.submit-form .commit').attr('disabled', 'disabled');
    var tagKeywords = new Array();
    $(this).find('.data-presenting span:not(:last-child)').each(function() {
        var value = $(this).text();
        tagKeywords.push(value);
    });
    var groupId = $('#moveTo').val();
    var pl = new SOAPClientParameters();
    if ($('.submit-form .commit').attr('id') == undefined) {
        groupId = $('#grouplist .expanded-folder').parent().attr('data-id');
        pl.add("tagName", tagName);
        pl.add("tagKeywords", tagKeywords.join(','));
        pl.add("groupId", groupId);
        SOAPClient.invoke("/m/", "createTag", pl, true, function(r) {
            if (r !== 'null' && r !== 'duplicate') {
                var tag = JSON.parse(r);
                var keywords = '';
                if (tag.keywords !== '')
                    keywords = '<span class="keywords" style="margin-left: 25px;color: #AAA;display: block;margin-top: -13px;">' + tag.keywords + '</span>';
                $('.widget-stream_list ul').append('<li class="mozaic-widget item-1000031974 folder-tab first widget-stream_item">' +
                        '<div class="social-profile-disconnected">' +
                        '<a class="expand-folder type-keyword">' +
                        '<i class="icon-stream-type icon-stream-market_terms-small"></i><span>' + tag.name + '</span>' + keywords +
                        '</a>' +
                        '<div class="buttons-container small">' +
                        '<div class="btn-holder edit-button">' +
                        /*'<a data-id="' + tag.id + '" groupid="' + tag.groupId + '" data-context="market_terms" data-type="keyword" class="edit-button btn btn-small">' +
                         '<i class="icon-edit"></i><span>Edit</span>' +
                         '</a>' +*/
                        '</div>' +
                        '<div class="btn-holder delete-button">' +
                        /*'<a data-id="' + tag.id + '" groupid="' + tag.groupId + '" data-type="keyword" class="insert-delete-form delete-button btn btn-small">' +
                         '<i class="icon-delete-folder"></i><span>Delete</span>' +
                         '</a>' + */
                        '</div>' +
                        '</div>' +
                        '</div>' +
                        '</li>');
                var timeout = setTimeout(function() {
                    $('#modal').removeClass('in');
                    startInterval(1);
                }, 500);
            }
            else {
                if (r === 'duplicate') {
                    var helpBlock = $('.widget-addtag_form .help-block');
                    helpBlock.css('color', 'red');
                    helpBlock.text('Tag \'' + tagName + '\' has already been taken.');
                    $('.submit-form .commit').removeAttr('disabled');
                }
            }
        });
    }
    else {
        var tagId = $('.submit-form .commit').attr('id');
        pl.add('tagId', tagId);
        pl.add("tagName", tagName);
        pl.add("tagKeywords", tagKeywords.join(','));
        pl.add("groupId", groupId);
        SOAPClient.invoke("/m/", "modifyTag", pl, true, function(r) {
            if (r === 'succeed') {
                curTag.children('span').first().text(tagName);
                if (curTag.children('.keywords').length === 0)
                    curTag.append('<span class="keywords" style="margin-left: 25px;color: #AAA;display: block;margin-top: -13px;">' + tagKeywords.join(',') + '</span>')
                else
                    curTag.children('.keywords').text(tagKeywords.join(','));
                if (groupId != curTag.next().find('a.edit-button').attr('groupid'))
                    curTag.animate({height: 0}, 200, function() {
                        curTag.remove();
                    });
            }
            var timeout = setTimeout(function() {
                $('#modal').removeClass('in');
                startInterval(1);
            }, 500);
        });
    }
    return false;
});

$(document).on('mouseover', '.dropdown-menu .dropdown-menu', function() {
    $(this).prev().css('color', '#FFF');
    $(this).prev().css('background-color', '#0088cc');
});

$(document).on('mouseleave', '.dropdown-menu .dropdown-menu', function() {
    $(this).prev().css('color', '');
    $(this).prev().css('background-color', '');
});

var curMessage;
$(document).on('click', '.mention-tag', function() {
    if (window.location.href.split('#')[1].split('/')[0] !== 'activity') {
        curMessage = $(this).parents('.widget-story_signal');
        var left = $(this).offset().left - curMessage.offset().left;
        var top = $(this).offset().top + $(this).height() * 3 / 4 + $('.list-viewport').scrollTop();
        $('#tagMenu').css('left', left + 'px');
        $('#tagMenu').css('top', top + 'px');
        $('#tagMenu').css('display', 'block');
        $('#tagMenu>ul>li').height($('#tagMenu').height());
    }
    else {
        curMessage = $(this).parents('li');
        var left = $(this).offset().left - curMessage.offset().left;
        var top = $(this).offset().top + $(this).height() * 3 / 4 + $('.list-viewport').scrollTop();
        $('#tagMenu').css('left', left + 'px');
        $('#tagMenu').css('top', top + 'px');
        $('#tagMenu').css('display', 'block');
        $('#tagMenu>ul>li').height($('#tagMenu').height());
    }
});

$(document).on('mouseleave', '#tagMenu', function() {
    $(this).css('display', 'none');
});

$(document).on('click', '#tagMenu .sub-menu a', function() {
    var streamId = curMessage.attr('streamid');
    var messageId = curMessage.attr('messageid');
    var pl = new SOAPClientParameters();
    pl.add("messageId", messageId);
    pl.add("tagId", $(this).parent().attr('data-id'));
    pl.add("streamId", streamId);
    SOAPClient.invoke("/m/", "addTag", pl, true, addTagCompleted);
});

function addTagCompleted(r) {
    if (r !== 'null') {
        var tag = JSON.parse(r);
        var twoTags = curMessage.find('.first-two-tags>div');
        if (twoTags.length > 0) {
            var tagHTML = '<div class="tag-holder-container"><label>' + tag.tagName + '</label><a tagid="' + tag.tagId + '" class="remove-tag">x</a></div>';
            twoTags.append(tagHTML);
            if (twoTags.children().length > 2) {
                //display more tag and add margin to tags
                curMessage.find('.more-tags-holder').css('display', 'block');
                twoTags.css('margin-right', '20px');
                var moreTags = curMessage.find('.more-tags-holder .widget-annotable_tags');
                if (moreTags.text().trim() !== '')
                    moreTags.append('<br>' + tag.tagName);
                else
                    moreTags.text(tag.tagName);
            }
        }
        else {
            var tagContainer = curMessage.find('.simple-tag');
            var tagHTML = '<div class="tag-holder-container"><label>' + tag.tagName + '</label><a tagid="' + tag.tagId + '" class="remove-tag">x</a></div>';
            tagContainer.append(tagHTML);
        }
    }
}

$(document).on('click', '.more-tags-holder', function() {
    curMessage = $(this).parents('.widget-story_signal');
    $(this).css('display', '');
    var twoTags = curMessage.find('.first-two-tags');
    $(this).parents('.widget-story_signal').find('.first-two-tags').removeClass('first-two-tags');
    twoTags.addClass('all-tags');
});

$(document).on('mouseleave', '.widget-story_signal', function() {
    var allTags = $(this).find('.all-tags');
    if (allTags.length === 1 && allTags.children().children().length > 2) {
        allTags.removeClass('all-tags');
        allTags.addClass('first-two-tags');
        $(this).find('.more-tags-holder').css('display', 'block');
        var tags = $(this).find('.tag-holder-container');
        var tagToolTip = $(this).find('.more-tags-container>div');
        tagToolTip.empty();
        for (i = 2; i < tags.length; i++) {
            if (tagToolTip.text().trim() === '')
                tagToolTip.append($(tags[i]).find('label').text());
            else
                tagToolTip.append('<br>' + $(tags[i]).find('label').text());
        }
    }
});

// remove tag
$(document).on('click', 'a.remove-tag', function() {
    curMessage = $(this).parents('.widget-story_signal');
    var streamId = curMessage.attr('streamid');
    var messageId = curMessage.attr('messageid');
    var threadId = curMessage.attr('threadid');
    var tagId = $(this).attr('tagid');
    var pl = new SOAPClientParameters();
    pl.add('tagId', tagId);
    pl.add('streamId', streamId);
    pl.add('messageId', messageId);
    curTag = $(this);
    SOAPClient.invoke('/m/', 'removeTag', pl, true, function() {
        var tagToolTip = curMessage.find('.more-tags-container>div');
        tagToolTip.empty();
        var tagsContainer = curTag.parent().parent();
        curTag.parent().remove();
        var tags = tagsContainer.children();
        if (tags.length > 2) {
            for (i = 2; i < tags.length; i++) {
                if (tagToolTip.text().trim() === '')
                    tagToolTip.append($(tags[i]).find('label').text());
                else
                    tagToolTip.append('<br>' + $(tags[i]).find('label').text());
            }
        }
        else {
            curMessage.find('.more-tags-holder').css('display', '');
            curMessage.find('.widget-annotable_tags').first().css('margin-right', '');
        }
    });
});

//edit tag
$(document).on('click', '.tags-view a.edit-button', function() {
    curTag = $(this).parent().parent().prev();
    var tagName = curTag.children('span').first().text();
    var keywords = curTag.children('.keywords').text();
    var tagId = $(this).attr('data-id');
    $('.modal-title').html("Edit Tag");
    $('.modal-body').html(addTag);
    var input = $('.modal-body .suggest-input input');
    input.css('width', ((input.val().length + 1) * 7.3) + 'px');
    var value = keywords;
    if (value.indexOf(',') !== -1) {
        values = value.split(',');
        for (i = 0; i < values.length; i++) {
            if (values[i] !== '')
                input.parent().before('<span class="email" email="' + values[i] + '">' + values[i] + '<i class="clear-icon"></i></span>');
        }
    }
    else if (value !== '') {
        input.parent().before('<span class="email" email="' + keywords + '">' + keywords + '<i class="clear-icon"></i></span>');
    }
    $('#grouplist>li').each(function() {
        var groupId = $(this).attr('data-id');
        var groupName = $(this).find('span').first().text();
        $('.bbf-form>*>div>* select').append('<option value="' + groupId + '">' + groupName + '</option>');
    });
    $('.bbf-form>*>div>* select').val($(this).attr('groupid'));
    $('#ftagName').val(tagName);
    $('.bbf-form>*>div>*').last().css('display', '');
    $('.modal-body .commit').attr('id', tagId);
    $('.modal-backdrop').css('display', 'block');
    $('#modal').css('width', '380px');
    $('#modal').css('margin-left', '-190px');
    $('.modal-backdrop').addClass('in');
    $('.modal-backdrop').css('z-index', '9999');
    $('#modal').css('z-index', '10000');
    $('#modal').addClass("in");
});

$(document).on('click', '.tags-view a.delete-button', function() {
    if (confirm("Are you sure to delete this tag?\nThis cannot be undone!")) {
        var tagId = $(this).attr('data-id');
        var pl = new SOAPClientParameters();
        pl.add('tagId', tagId);
        curTag = $(this).parents('li');
        SOAPClient.invoke("/m/", "deleteTag", pl, true, function() {
            curTag.animate({height: 0}, 200, function() {
                $(this).remove();
            });
        });
    }
});

var curGroup;
$(document).on('click', '#grouplist a.btn', function() {
    curGroup = $(this).parents('li.folder-tab');
    var groupId = $(this).attr('taggroup');
    var pl = new SOAPClientParameters();
    switch ($(this).children('i').attr('class')) {
        case "icon-delete":
            if (confirm("All tags in this folder will be deleted.\nThis cannot be undone!")) {
                pl.add('groupId', groupId);
                SOAPClient.invoke("/m/", "deleteGroup", pl, true, function(r) {
                    if (r == 'succeed') {
                        curGroup.animate({height: 0}, 200, function() {
                            $(this).remove();
                            $('#all-groups').click();
                        });
                    }
                });
            }
            break;
        case "icon-edit":
            $('.modal-title').html("Edit Group");
            $('.modal-body').html(addTagGroup);

            $('.modal-backdrop').css('display', 'block');
            $('#modal').css('width', '380px');
            $('#modal').css('margin-left', '-190px');
            $('.modal-backdrop').addClass('in');
            $('.modal-backdrop').css('z-index', '9999');
            $('#modal').css('z-index', '10000');
            $('#modal').addClass("in");
            $('#tagGroupName').val(curGroup.find('a#folder-tab span').text());
            $('.modal-body .commit').attr('id', $(this).attr('taggroup'));
            break;
    }
});
/* end tag group */

/**
 * Source filter on top source
 */

$(document).on('click', '.source-filter', function() {
    $('#source-filter-widget a').first().attr('data-value', $(this).text());
    $('#source-filter-widget span').first().text($(this).text());
    $('#source-filter-widget>div').addClass('selected');
    $('.url-widget-link').first().click();
    return false;
})

/* cookie */

function setCookie(c_name, value, exdays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
    document.cookie = escape(c_name) + "=" + escape(c_value);
}

function getCookie(c_name) {
    var i, x, y, ARRcookies = document.cookie.split(";");
    for (i = 0; i < ARRcookies.length; i++) {
        x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
        y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
        x = x.replace(/^\s+|\s+$/g, "");
        if (x == escape(c_name)) {
            return unescape(y).split(';')[0];
        }
    }
}
/* end cookie */

/* monitoring */
function loadMonitoring(v)
{
    dateFrom = $('#selected_date').attr('datefrom');
    dateTo = $('#selected_date').attr('dateto');
    userId = $('#user-filter-widget').find('a').attr('data-value');
    var filter = {};
    filter.view = v;
    filter.dateFrom = dateFrom;
    filter.dateTo = dateTo;
    filter.userId = userId;
    curRequests.push($.get('/ws/monitoring/' + JSON.stringify(filter), function(data) {
        if ($('.background-loading').css('opacity') == 1) {
            $('.background-loading').animate({'opacity': 0}, 100);
            $('.list-viewport').animate({'opacity': 1}, 500);
        }
        $('.moni-table').html(data);
        $(document).ready(function() {
            $("#moniList").dataTable({
                "sPaginationType": "full_numbers",
            });
            $("#doSearch").keyup(function() {
                $("#moniList_filter input").val($(this).val());
                $("#moniList_filter input").keyup();
            });
        });
    }));
}

/* end monitoring */

/* sentiment chart */

//change trend type
$(document).on('click', '.sentiment-trend', function() {
    if (!$(this).hasClass('selected')) {
        var type = $('.sentiment-block-graph li.selected').text().toLowerCase();
        $('.sentiment-trend.selected').removeClass('selected');
        $(this).addClass('selected');
        if ($('.sentiment-trend.selected').text() === 'SENTIMENT TREND')
            drawPercentTrend(sentimentData, 'normal', false, type);
        else
            drawPercentTrend(sentimentData, 'percent', true, type);
    }
});

$(document).on('click', '.sentiment-block-graph .hourly-filter-wrapper li', function() {
    if (!$(this).hasClass('selected')) {
        $('.sentiment-block-graph .hourly-filter-wrapper li.selected').removeClass('selected');
        $(this).addClass('selected');
        if ($('.sentiment-trend.selected').text() === 'SENTIMENT TREND')
            drawPercentTrend(sentimentData, 'normal', false, $(this).text().toLowerCase());
        else
            drawPercentTrend(sentimentData, 'percent', true, $(this).text().toLowerCase());
    }
});

/* sentiment chart */


/* email subscription */

$(document).on('mouseover', '.keyword-subscription-search-box .results li', function(e) {
    $('.keyword-subscription-search-box .results li.active').removeClass('active');
    $(this).addClass('active');
});

$(document).on('keydown', '.keyword-subscription-search-box input.search-box', function(e) {

    switch (e.keyCode) {
        case 13:
            $(this).val('');
            $('.keyword-subscription-search-box .results').css('display', 'none');
            $('.keyword-subscription-search-box .results li.active').removeClass('active').css('display', 'none');
            break;
        case 38: //up
            var active = $('.keyword-subscription-search-box .results li.active');
            if ($('.keyword-subscription-search-box .results li').length == 1) {
                $('.keyword-subscription-search-box .results li').last().addClass('active');
                break;
            }
            if (active.length == 0) {
                var active = $('.keyword-subscription-search-box .results li').last();
                active.addClass('active');
                $('.keyword-subscription-search-box .results').scrollTop($('.keyword-subscription-search-box .results')[0].scrollHeight);
            } else {
                active.removeClass('active');
                while (active.prev().css('display') == 'none') {
                    active = active.prev();
                }
                if (active.prev().length != 0) {
                    active.prev().addClass('active');
                    var top = $('.keyword-subscription-search-box .results li.active').position().top + $('.keyword-subscription-search-box .results').scrollTop();
                    var height = $('.keyword-subscription-search-box .results li.active').height();
                    if (top < $('.keyword-subscription-search-box .results').scrollTop()) {
                        $('.keyword-subscription-search-box .results').scrollTop(top);
                    }
                }
                else {
                    active = active.parent().children().last();
                    while (active.prev().css('display') == 'none') {
                        active = active.prev();
                    }
                    active.addClass('active');
                    active.parent().scrollTop($('.keyword-subscription-search-box .results')[0].scrollHeight);
                }
            }
            return false;
            break;
        case 40: //down
            var active = $('.keyword-subscription-search-box .results li.active');
            if ($('.keyword-subscription-search-box .results li').length == 1) {
                $('.keyword-subscription-search-box .results li').first().addClass('active');
                break;
            }
            if (active.length == 0) {
                var active = $('.keyword-subscription-search-box .results li').first();
                active.addClass('active');
                $('.keyword-subscription-search-box .results').scrollTop(0);
            } else {
                active.removeClass('active');
                while (active.next().css('display') == 'none') {
                    active = active.next();
                }
                if (active.next().length != 0) {
                    active.next().addClass('active');
                    var top = $('.keyword-subscription-search-box .results li.active').position().top + $('.keyword-subscription-search-box .results').scrollTop();
                    var height = $('.keyword-subscription-search-box .results li.active').height();
                    if (top + height > $('.keyword-subscription-search-box .results').scrollTop() + $('.keyword-subscription-search-box .results').height()) {
                        $('.keyword-subscription-search-box .results').scrollTop(top - $('.keyword-subscription-search-box .results').height() + height);
                    }
                }
                else {
                    active = active.parent().children().first();
                    while (active.next().css('display') == 'none') {
                        active = active.next();
                    }
                    active.addClass('active');
                    active.parent().scrollTop(0);
                }
            }
            return false;
            break;
        default:
            if ($('.keyword-subscription-search-box .results li.active').length == 0)
                $('.keyword-subscription-search-box .results li').first().addClass('active');
            $('.keyword-subscription-search-box .results').css('display', 'block');
            break;
    }
});

$(document).on('keyup', '.keyword-subscription-search-box input.search-box', function() {
    var textVal = $(this).val();
    $('.keyword-subscription-search-box .results li').each(function() {
        if (textVal == '') {
            $(this).show();
        }
        else {
            if ($(this).text().toLowerCase().indexOf(textVal.toLowerCase()) == -1) {
                $(this).hide();
            }
        }
    });
    if ($('.keyword-subscription-search-box .results li.active').css('display') === 'none') {
        var active = $('.keyword-subscription-search-box .results li').first();
        while (active.next().css('display') == 'none') {
            active = active.next();
        }
        active.addClass('active');
    }
});

$(document).on('blur', '.keyword-subscription-search-box input.search-box', function() {
    $('.keyword-subscription-search-box .results').hide();
});

$(document).on('focus', '.keyword-subscription-search-box input.search-box', function() {
    $('.keyword-subscription-search-box .results').show();
});

/* end email subscription */

$(document).keydown(function(e) {
    if (window.location.href.split('#')[1].split('/')[0] == 'metrics')
        if (e.keyCode == 72 && e.altKey) {
            if ($('.left-nav').hasClass('hide')) {
                //show the content
                $('.left-nav').removeClass('hide');
                $('#controller-container>.content').css('margin-left', '');
            }
            else {
                //hide the content
                $('.left-nav').addClass('hide');
                $('#controller-container>.content').css('margin-left', '70px');
            }
            $(window).resize();
            return false;
        }
});